Last active
September 9, 2019 12:06
-
-
Save mllnd/914c152e88b59c8bc514b086513cff78 to your computer and use it in GitHub Desktop.
Bubble Sort for ICS0017
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 <memory.h> | |
int* Bubble(int length, int* array) { | |
// Allocate new array and clone it | |
size_t copy_size = sizeof(int) * length; | |
int *array_copy = malloc(copy_size); | |
memcpy(array_copy, array, copy_size); | |
int temp_int; | |
for (int k = 0; k < length-1; k++) { | |
for (int i = 0; i < length-k-1; i++) { | |
if (array_copy[i] > array_copy[i+1]) { | |
temp_int = array_copy[i]; | |
array_copy[i] = array_copy[i+1]; | |
array_copy[i+1] = temp_int; | |
} | |
} | |
} | |
return array_copy; | |
}; | |
int main() { | |
// Settings | |
int max_array_size = 10; | |
int min_array_size = 1; | |
int max_array_value = 50; | |
// Seed random generator | |
srand(time(NULL)); | |
// Random size | |
int array_size = (rand() % (max_array_size - min_array_size)) + min_array_size; | |
int integers[array_size]; | |
// Populate the array with integers | |
for (int i = 0; i < array_size; i++) { | |
integers[i] = rand() % max_array_value; | |
printf("%d ", integers[i]); | |
} | |
int *sorted = Bubble(array_size, integers); | |
printf("\nSorted:\n"); | |
for (int i = 0; i < array_size; i++) { | |
printf("%d ", sorted[i]); | |
} | |
free(sorted); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment