Created
August 5, 2015 08:09
-
-
Save bararchy/e1aef7c2d36f39098765 to your computer and use it in GitHub Desktop.
Bubble sort
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 <string.h> | |
#include <time.h> | |
#include <unistd.h> | |
void shuffle(int *array, size_t n); | |
void print_array(int *my_array, int array_size); | |
int main(int argc, char *argv[]){ | |
int array_create_size = atoi(argv[1]); | |
if (array_create_size < 1){ | |
printf("Input must be a positive integer !\n"); | |
return 1; | |
} | |
// Genereate the array | |
int my_array[array_create_size]; | |
for (int i = 0; i <= array_create_size; i++){ | |
my_array[i] = i; | |
} | |
// Print my array | |
print_array(my_array, array_create_size); | |
printf("Suffeled Array: \n"); | |
// Shuffle the array and print it | |
shuffle(my_array, array_create_size); | |
print_array(my_array, array_create_size); | |
// Now lets try to sort using bubble | |
printf("Now, let sort the array using bubble sort\n"); | |
sleep(1); | |
int sorted = 1; | |
while (sorted == 1){ | |
for (int i = 0; i <= array_create_size; i++){ | |
if (i + 1 <= array_create_size ){ | |
if (my_array[i] > my_array[i+1]){ | |
int a = my_array[i]; | |
int b = my_array[i+1]; | |
// switch | |
my_array[i] = b; | |
my_array[i+1] = a; | |
//sorted = 0; | |
} | |
else{ | |
//sorted = 1; | |
} | |
} | |
usleep(20000); | |
printf("Sorting: \n"); | |
print_array(my_array, array_create_size); | |
} | |
} | |
} | |
void print_array(int *my_array, int array_size){ | |
printf("["); | |
for (int i = 0; i <= array_size; i++){ | |
printf("%d, ", my_array[i]); | |
} | |
printf("]\n"); | |
} | |
void shuffle(int *array, size_t n) { | |
struct timeval tv; | |
gettimeofday(&tv, NULL); | |
int usec = tv.tv_usec; | |
srand48(usec); | |
if (n > 1) { | |
size_t i; | |
for (i = n - 1; i > 0; i--) { | |
size_t j = (unsigned int) (drand48()*(i+1)); | |
int t = array[j]; | |
array[j] = array[i]; | |
array[i] = t; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Bubble sort code