From 64c7d82240c50b00a4b04c911b198fefc1c8caf9 Mon Sep 17 00:00:00 2001 From: AustrianToast Date: Thu, 23 Nov 2023 00:04:22 +0100 Subject: [PATCH] basics done only supports bubble sort --- main.c | 91 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 main.c diff --git a/main.c b/main.c new file mode 100644 index 0000000..95da7cd --- /dev/null +++ b/main.c @@ -0,0 +1,91 @@ +#include +#include +#include +#include + +#define MAX_ITERATIONS 100 +#define DESIRED_ARRAY_LENGTH 10 +#define MAX_VALUE 1000 +#define QUIT 3 + +void print_array(int array[], size_t array_length) { + for(size_t index = 0; index < array_length; index++) { + printf("%d", array[index]); + if(index < array_length -1) { + printf(", "); + } + } + printf("\n"); +} + +// I implemented this using the pseudocode which can be found in wikipedia +// https://en.wikipedia.org/wiki/Bubble_sort#Pseudocode_implementation +void bubble_sort(int array[], size_t array_length) { + size_t n = array_length; + + while(n > 1) { + size_t new_n = 0; + for(size_t i = 1; i <= n -1; i++) { + if(array[i-1] > array[i]) { + int value_to_swap = array[i]; + array[i] = array[i-1]; + array[i-1] = value_to_swap; + + new_n = i; + } + } + n = new_n; + } + return; +} + +void fill_array(int array[], size_t array_length) { + struct timespec ts; + timespec_get(&ts, TIME_UTC); + srand(ts.tv_nsec); + + for(size_t i = 0; i < array_length; i++) { + array[i] = rand() & MAX_VALUE; // limits the number to 100 + } + return; +} + +void print_menu() { + printf("Here are the possible options:\n"); + printf("\t1) print array\n"); + printf("\t2) bubble sort\n"); + printf("\t%d) quit\n", QUIT); + return; +} + +int main() { + int iterations = 0; + int option = EOF; + size_t array_length = DESIRED_ARRAY_LENGTH; + int array[array_length]; + fill_array(array, array_length); + + while(option != QUIT) { + if(iterations >= MAX_ITERATIONS) { + printf("loop detected. stopping...\n"); + return 1; + } + + print_menu(); + int success = scanf("%d", &option); // breaks if inputing a char + + if(success == 1 && option > 0 && option < QUIT) { + iterations = 0; + switch (option) { + case 1: + print_array(array, array_length); + break; + case 2: + bubble_sort(array, array_length); + break; + } + } + iterations++; + } + return 0; +} \ No newline at end of file