SortingAlgorithms/ShakerSort/ShakerSort.pde
2022-05-15 17:10:16 +02:00

118 lines
2.8 KiB
Plaintext

final float timeout = 2.5;
final int aMin = 100;
final int aMax = 500;
final int repeats = 4;
ArrayList<Integer> bars;
float barWidth;
int amount;
int sortOnLeft = 0, sortOnRight = 0;
int current = 1;
boolean complete = false;
boolean direction = true;
boolean hasSwitched = false;
float tenPercentHeight;
float ninetyPercentHeight;
int sortedFrameCountCapture = -1;
void setup() {
fullScreen(P3D);
// size(1280, 720, P3D);
tenPercentHeight = height * 0.1;
ninetyPercentHeight = height * 0.9;
amount = floor(random(aMin, aMax));
bars = new ArrayList<Integer>();
for (int i = 0; i < amount; i++) {
bars.add(floor(random(tenPercentHeight, ninetyPercentHeight)));
}
barWidth = (float)width / amount;
// frameRate(amount);
frameRate(1000);
}
void draw() {
background(0);
stroke(0);
for (int i = 0; i < bars.size(); i++) {
if (i == sortOnLeft && !complete) {
fill(255, 0, 0);
} else if (i == amount-1-sortOnRight && !complete) {
fill(255, 0, 0);
} else if (i == current && !complete) {
fill(0, 255, 0);
} else {
fill(255);
}
rect(i * barWidth, height-bars.get(i), barWidth, bars.get(i));
}
fill(255);
stroke(255);
textAlign(LEFT, TOP);
textSize(width*0.022);
text("Bar Amount: "+amount+"; FPS: "+round(frameRate)+";", 0, 0);
for (int j = 0; j < repeats; j++) {
if (!complete) {
final int tempValue = bars.get(current);
if (tempValue < bars.get(current-1)) {
bars.set(current, bars.get(current-1));
bars.set(current-1, tempValue);
hasSwitched = true;
}
if (current == amount-1-sortOnRight && direction) {
direction = !direction;
sortOnRight++;
if (hasSwitched == false) {
complete = true;
}
hasSwitched = false;
} else if (current == sortOnLeft+1 && !direction) {
direction = !direction;
sortOnLeft++;
if (hasSwitched == false) {
complete = true;
}
hasSwitched = false;
} else {
if (direction) {
current++;
} else {
current--;
}
}
if (sortOnLeft+1 == amount-1-sortOnRight) {
complete = true;
}
if (complete) {
sortedFrameCountCapture = frameCount;
}
} else if (sortedFrameCountCapture != -1 && frameCount-sortedFrameCountCapture >= amount*timeout) {
sortedFrameCountCapture = -1;
current = 1;
complete = false;
sortOnLeft = 0;
sortOnRight = 0;
direction = true;
hasSwitched = false;
amount = floor(random(aMin, aMax));
bars = new ArrayList<Integer>();
for (int i = 0; i < amount; i++) {
bars.add(floor(random(tenPercentHeight, ninetyPercentHeight)));
}
barWidth = (float)width / amount;
// frameRate(amount);
}
}
}