36 lines
777 B
C
36 lines
777 B
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <time.h>
|
|
|
|
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;
|
|
}
|