Created
February 13, 2023 20:32
-
-
Save ameoverflow/40947f7958cb4494b1914b96987fc653 to your computer and use it in GitHub Desktop.
lmao bogosort
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <time.h> | |
#include <stdbool.h> | |
bool is_sorted(int *a, int n) | |
{ | |
while ( --n >= 1 ) { | |
if ( a[n] < a[n-1] ) return false; | |
} | |
return true; | |
} | |
void shuffle(int *a, int n) | |
{ | |
int i, t, r; | |
for(i=0; i < n; i++) { | |
t = a[i]; | |
r = rand() % n; | |
a[i] = a[r]; | |
a[r] = t; | |
} | |
} | |
int main(int argc, char *argv[]) | |
{ | |
if (argc < 2) { | |
printf("Usage: bogosort <array size>"); | |
return 1; | |
} | |
int array_size = atoi(argv[1]); | |
printf("Creating an array with %i elements\n", array_size); | |
int data[array_size]; | |
for (int i = 0; i < array_size; i++) { | |
data[i] = i; | |
} | |
shuffle(data, array_size); | |
printf("Sorting...\n"); | |
time_t start = time(NULL); | |
long long runs = 0; | |
while ( !is_sorted(data, array_size) ) { | |
shuffle(data, array_size); | |
runs++; | |
} | |
time_t end = time(NULL); | |
time_t diff = end - start; | |
printf("Sorted in %ld seconds in %i runs\n", diff, runs); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment