90 lines
2.2 KiB
C
90 lines
2.2 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <time.h>
|
|
|
|
#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;
|
|
} |