diff --git a/bogosort.c b/bogosort.c new file mode 100644 index 0000000..bd74440 --- /dev/null +++ b/bogosort.c @@ -0,0 +1,36 @@ +#include +#include +#include + +void shuffle(int* data, unsigned int n) { + for(unsigned int i = 0; i < n - 1; i++) { + unsigned int j = i + rand() % (n - i); + int tmp = data[i]; + data[i] = data[j]; + data[j] = tmp; + } +} + +int sorted(int* data, unsigned int n) { + for(unsigned int i = 1; i < n; i++) { + if(data[i-1] > data[i]) return 0; + } + return 1; +} + +void bogosort(int* data, unsigned int n) { + unsigned int i = 1; + do { + shuffle(data, n); + i++; + } while(!sorted(data,n)); + printf("%u iterations for %u elements\n", i, n); +} + +int main( int argc, char *argv[] ) { + srand((size_t) time(NULL)); + int data[10] = { 4,2,1,3,8,7,5,6,9,0 }; + + bogosort(data,10); + return 0; +}