Skip to content

Instantly share code, notes, and snippets.

@pdsouza29
Created November 15, 2011 01:56
Show Gist options
  • Save pdsouza29/1365882 to your computer and use it in GitHub Desktop.
Save pdsouza29/1365882 to your computer and use it in GitHub Desktop.
Bogosort
/* Preetam D'Souza
* BOGOSORT
* 11.14.2011
*/
// HAPPY BIRTHDAY BOGO!
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 50
void print_array(int n, int *a) {
int i;
for(i=0;i<n;i++)
printf("%d ", a[i]);
printf("\n");
}
int sorted(int n, int *a) {
int i;
for(i=0;i<n-1;i++)
if(a[i] > a[i+1])
return 0;
return 1;
}
// Fisher-Yates shuffle [Durstenfeld's version]
void bogosort(int n, int *a) {
int i, j, tmp;
for(i=n-1;i>0;i--) {
j = (int) rand() % (i+1);
tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}
int main() {
int a[N], i=0, n=0;
printf("Enter some numbers (one number per line, type 'done' when done)\n");
while(scanf("%d", a+(n++))) { printf("Succesfully read number!\n"); }
printf("\nOk, here's your list of numbers: ");
print_array(n-1, a);
printf("\nBogosorting...");
fflush(stdout);
while(!sorted(n-1, a)) {
bogosort(n-1, a);
usleep(250000);
printf(".");
fflush(stdout);
++i;
}
printf("\n\nSuccess! Bogosort finished in %d iterations.\n", i);
print_array(n-1, a);
}
SAMPLE OUTPUT:
preetam-dsouzas-macbook-pro:random chaoticryld$ ./a.out
Enter some numbers (one number per line, type 'done' when done)
4
Succesfully read number!
7
Succesfully read number!
5
Succesfully read number!
6
Succesfully read number!
done
Ok, here's your list of numbers: 4 7 5 6
Bogosorting...................................................................
Success! Bogosort finished in 64 iterations.
4 5 6 7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment