I recently programmed a visualization of the bubble sorting algorithm that, while works, takes a significant chunk of time and energy to run. My question is... Is there a better way to do this?
Side note, a feature I'm interested in implementing is that, whenever a swap is made, the program makes a sound (I included the library in the code)
import processing.sound.*;
SinOsc sine;
int numOfEntries = 200;
int rectWidth;
int randomUnsortedArray[] ;
void setup()
{
size(1000, 1000);
background(255);
randomUnsortedArray = new int[numOfEntries];
rectMode(CORNERS);
for (int i = 0; i < numOfEntries; i++)
{ //Gives each element in the array a random value
randomUnsortedArray[i] = int(random(height));
}
}
void draw()
{
frameRate(120);
randomUnsortedArray = bubbleSort(randomUnsortedArray);
for (int i = 0; i < numOfEntries; i++)
{
fill(255);
rect(i*rectWidth, height, rectWidth*(i+1), height-randomUnsortedArray[i]);
}
}
int numOfComparisons =0;
int [] bubbleSort(int unsortedArray[])
{
background(0);
float rectWidth = width/unsortedArray.length;
boolean swap;
for (int h = 0; h < numOfEntries; h++)
{ //Redraws entire array of rectangles
fill(255);
rect(h*rectWidth, height, rectWidth*(h+1), height-randomUnsortedArray[h]);
}
swap=false;
for (int i = 0; i < unsortedArray.length - 1; i++)
{
if (unsortedArray[i] > unsortedArray[i+1])
{
fill(90, 132, 78);
rect(rectWidth*(i+1), height, rectWidth*(i+2), height-unsortedArray[i+1]);
sine = new SinOsc(this);
sine.play(); //Program eventually crashes
//begin swap
int temp = unsortedArray[i];
unsortedArray[i] = unsortedArray[i+1];
unsortedArray[i+1]= temp;
swap = true;
//end swap
numOfComparisons++;
print("Number of Comparisons: " +numOfComparisons + "\n");
break;
}
}
return unsortedArray;
}