Jump to content

Stupid sort/Bogo-sort

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by 24.60.20.159 (talk) at 21:39, 6 October 2002. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)

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:

  1. 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)