Stupid sort/Bogo-sort
Appearance
Bogosort: According to the Jargon File, it is "the archetypal perversely awful algorithm." and it is "equivalent to repeatedly throwing a deck of cards in the air, picking them up at random, and then testing whether they are in order." Worst-case analysis complexity is O(n!). C code snippet follows:
- define length(A) n
void bogo_sort (int *A, int length) {
int i, j; srand (time(0)); while (!sorted(A, length)) { B = make_visited (length); for (i = 0; i < length; ++i) { j = rand () % length; if ((!*(B+j))) { swap (*(A+i),*(A+j)); (*(B+j))++; } } }
}
int sorted (int *A, int length) {
int i; for (i = 0; i < length-1; ++i) if (*(A+i) > *(A+(i+1))) return 0; return 1;
}
int *make_visited (int k) {
int i, *C = malloc (k*sizeof(int)); for (i = 0; i < k; ++i) *(C+i) = 0; return C;
}
void swap (int &i, int &j) {
int temp = i; i = j; j = i;
}
References:
http://www.tuxedo.org/jargon/ (The Jargon File 4.1.0)