Skip to content

Instantly share code, notes, and snippets.

@yeppiidev
Created August 24, 2023 13:25
Show Gist options
  • Save yeppiidev/83a8d6ac0f1fa0e35526cec8e5654eef to your computer and use it in GitHub Desktop.
Save yeppiidev/83a8d6ac0f1fa0e35526cec8e5654eef to your computer and use it in GitHub Desktop.
A visual demo of bubblesort and bogosort in Processing 3 (rename .java to .pde)
import processing.sound.*;
final int BUBBLE_SORT = 0;
final int BOGO_SORT = 1;
final int HIGHLIGHT_AREA = 2;
int[] nums;
int activeElem;
int ci, cj = 1;
int activeSort = BUBBLE_SORT;
boolean sortInProgress = true;
boolean sortComplete = false;
TriOsc triangle;
void shuffle() {
// shuffle
for (int i = nums.length - 1; i > 0; i--)
{
// get random item from the numsay
int index = (int)random(i + 1);
// simple swap
int old = nums[index];
nums[index] = nums[i];
nums[i] = old;
}
}
boolean sorted() {
for (int i = 1; i < nums.length; i++)
{
if (nums[i] < nums[i - 1])
{
return false;
}
}
return true;
}
void bogoSort() {
sortComplete = false;
for (int i = 1; i < nums.length; i++)
{
if (!(nums[i] < nums[i - 1]))
{
shuffle();
triangle.freq(nums[i]);
activeElem = i;
}
}
}
void bubbleSort() {
int n = nums.length;
int temp = 0;
if (ci > n) {
sortComplete = true;
ci = 0;
} else {
sortComplete = false;
}
ci++;
for (int j = 1; j < (n - ci); j++) {
if (nums[j - 1] > nums[j]) {
// swap elements
temp = nums[j - 1];
nums[j - 1] = nums[j];
nums[j] = temp;
activeElem = j;
triangle.freq(nums[j]);
}
}
}
void setup() {
size(800, 800, P2D);
nums = new int[100];
for (int i = 0; i < nums.length; i++) {
nums[i] = i * 10;
}
shuffle();
triangle = new TriOsc(this);
}
void draw() {
background(1);
switch (activeSort) {
case BUBBLE_SORT:
bubbleSort();
break;
case BOGO_SORT:
bogoSort();
break;
default:
fill(255, 0, 0);
rect(0, 0, width, height);
break;
}
for (int it = 0; it < nums.length; it++) {
if (it > activeElem - HIGHLIGHT_AREA && it < activeElem + HIGHLIGHT_AREA) fill(255, 0, 0);
else fill(255);
if (sortComplete) fill(0, 255, 0);
rect(it * 10, height - nums[it], 10, nums[it]);
}
triangle.play();
}
void keyPressed() {
if (key == 'a') {
activeSort = BOGO_SORT;
} else if (key == 'b') {
activeSort = BUBBLE_SORT;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment