I fault myself for taking my eye so off the ball (misspent years!) I had not seen the Sleep Sort until a friend (?) showed me this. I don't recognize the language but can see how it works:
const arr = [120, 5, 100,1, 90, 200, 40, 29];
for (let item of arr){
setTimeout ( () =>
console. log (item), item)
}
which while not presented in the context of a full compiles we can play with it ourselves example is nevertheless a remarkably compact implementation of the algorithm.
All good questions one might ask of any "new" sorting idea. Can there be new ideas? I certainly hope so, but around sorting I would expect it all to have been pretty much sorted.
Revolutionary: click bait, sry.
Different: it uses a method I had not seen and can only imagine the kind of brain that dreamt it up. I dunno who claims it; I found more than one person who at least implied they created it.
Special features: Use, or more accurately abuse of system timing or task schedulers or whatever.
Scaling: It doesn't do negative numbers, unless as someone clever observed "Negative numbers will simply cause the print to be executed in the past. This would still result in the same order." And of course if you numbers are 20000 and 30000 and like that, it can take some large amount of real time.
Read and see implementations in a variety of languages:
The Sleep Sort is also not stable.
The incrementing counter fixes the millis() problem, but moves the algorithm away from its charter - use of time.
Another sort of sort that turns up when searching for fun and meaning I present here. I'll drop a clue for y'all by naming it the Fisher-Yates sort:
int input[] = {4, 1, 5, 9, 2, 6,}; // 5, 3, }; // 8 takes long enough, haven't tried 9
int n = sizeof input / sizeof *input;
void setup() {
Serial.begin(9600);
Serial.print("Initial array: ");
printArray(input, n);
sort(input, n);
Serial.print("Sorted array: ");
printArray(input, n);
}
void loop() {
}
void sort(int *arr, int n) {
while (!test(arr, n))
shuffle(arr, n);
}
bool test(int *arr, int n) {
for (int ii = 0; ii < n - 1; ii++) {
if (arr[ii] > arr[ii + 1]) {
return false;
}
}
return true;
}
void shuffle(int *arr, int n) {
for (int ii = n - 1; ii > 0; ii--) {
int jj = random(ii + 1);
int temp = arr[ii];
arr[ii] = arr[jj];
arr[jj] = temp;
}
}
void printArray(int *arr, int n) {
for (int ii = 0; ii < n; ii++) {
Serial.print(arr[ii]);
Serial.print(" ");
}
Serial.println();
}
This is a horrible algorithm but it does work, eventually. Or does it? I wonder if the PRNG might get into some rhythm with the process and cause it to enter into an infinite loop.
I put this in General as in the past stuff that does not have questions about programming and/or is presented for amusement purposes or to stimulate conversation has been summarily moved out of Programming. To General.
a7