There are excellent books about the theory of sorting algorithms, and the net is full of videos. But can you do it yourself? Yes, you can. Just make use of the Serial Plotter that comes with the Arduino IDE for free.
To visualize the procedure, we use a set of columns of random heights, and draw them one next to the other on the plotter. The most simple algorithm which is called Bubble-Sort, will compare two adjacent columns and in case they are not in order they have to be swapped. To indicate which columns have to be swapped, two markers are shown below the columns.
If you use the old Arduino IDE the plotter always shows 500 samples. As we need 3 samples to draw one column we get 166 colums. If you use the new IDE whose plotter only offers 50 samples you only get 16 columns.
As the number of swappings goes with the square of the number of columns, one goes really fast, and the other will takes ages. As you can see, checking the "magic number" 10607 the sketh can detect the number of points of the plotter.
#if ARDUINO == 10607
const int N = 50 / 3; // IDE 2.0
#else
const int N = 500 / 3;
#endif
int a[N];
int b[N];
void setup() {
Serial.begin(115200);
Serial.println(__FILE__);
for (int i = 0; i < N; i++) {
a[i] = random(100);
print(0, a[i]);
}
boolean sorted = true;
do {
for (int i = 0; i < N - 1; i++) {
for (int j = 0; j < N; j++) b[j] = -20;
//for (int j = i + 1; j < N; j++)
if (a[i] > a[i + 1]) {
// indicate exchange candidates:
b[i] = -10;
b[i + 1] = -10;
printAll();
// now exchange both values_
int h = a[i];
a[i] = a[i + 1];
a[i + 1] = h;
sorted = false;
delay(1000);
break;
}
}
} while (!sorted);
printAll();
}
void loop() {}
void printAll() {
for (int j = 0; j < N; j++) {
print(b[j], a[j]);
print(b[j], a[j]);
print(-20, 0);
}
print(0, 0);
}
void print(int a, int b) {
Serial.print(a);
Serial.print(" ");
Serial.println(b);
}
Comments