We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hello everyone, I'm new to processing and made a simple visualization of a sorting algorithm. I've noticed it's very slow even though it is not very complicated...
Code:
final int LEN = 91;
int frame = 0, i = 0, j = 0;
float density = 6, cmp1X = 0, cmp2X = 0;
boolean switched = false;
float[] random = new float[LEN];
void setup()
{
size(630, 360, P2D);
frameRate(600);
background(51);
noStroke();
float rnd, temp;
for(int i = 0; i < LEN; i++)
{
random[i] = i * 3.7;
}
for(int i = 0; i < LEN; i++)
{
for(int j = 0; j < LEN; j++)
{
rnd = (int)(Math.random() * 100);
if(rnd % 2 == 0)
{
temp = random[i];
random[i] = random[j];
random[j] = temp;
}
}
}
/**
for(int i = 0; i < LEN; i++)
{
rnd = (float) Math.random() * 360;
random[i] = rnd;
}
*/
}
void draw()
{
background(51);
printArr();
float temp;
switched = false;
if((i < LEN && j < LEN) && random[i] > random[j])
{
switched = true;
cmp1X = i;
cmp2X = j;
temp = random[i];
random[i] = random[j];
random[j] = temp;
}
if(switched)
{
printArr();
}
i++;
if(i > LEN - 1 && j < LEN - 1)
{
i = 0;
j++;
}
}
void printArr()
{
background(51);
for(int x = 0; x < LEN; x++)
{
if(x == cmp1X && switched)
{
fill(1);
rect(x*7, 360 - random[x], density, random[x]);
}
else if(x == cmp2X && switched)
{
fill(100);
rect(x*7, 360 - random[x], density, random[x]);
}
else
{
fill(255);
rect(x*7, 360 - random[x], density, random[x]);
}
}
}
Answers
JUST read it slowly
Line 45 not needed
line 44 not needed
Lines 75 and 80 the && switched is not needed
first up, random[i] is confusing. don't name variables after keywords.
i suspect that line 48 means that there are lots of frames where nothing happens because the condition isn't true.
in fact, i added
inside the condition and it printed
so, yes, there are sometimes 40 or 90 frames where nothing is drawn.
this is probably the big problem though
your i is always iterating all the way through the set. you could stop when you've gone beyond the current end (j)