diff --git a/src/bsrch.c b/src/bsrch.c index 8f5cb7f..64cbfad 100644 --- a/src/bsrch.c +++ b/src/bsrch.c @@ -6,6 +6,7 @@ int bsrch(int target, int* arr, size_t n) { + // TODO: Find a way to error if list is out of order bool found = false; int start = 0, end = n - 1; if (arr[start] > target || arr[end] < target) return -1; diff --git a/src/bubble.c b/src/bubble.c new file mode 100644 index 0000000..5c7a727 --- /dev/null +++ b/src/bubble.c @@ -0,0 +1,20 @@ +#include "bubble.h" + +#include + + +void bubblesort(int* arr, size_t n) +{ + for (int i = 0; i < n; i++) + { + for (int elem = 0; elem < n - 1 - i; elem++) + { + if (arr[elem] > arr[elem + 1]) + { + int temp = arr[elem]; + arr[elem] = arr[elem + 1]; + arr[elem + 1] = temp; + } + } + } +} diff --git a/src/bubble.h b/src/bubble.h new file mode 100644 index 0000000..39d0387 --- /dev/null +++ b/src/bubble.h @@ -0,0 +1,5 @@ +#pragma once +#include + + +void bubblesort(int* arr, size_t n); diff --git a/src/ceesort.c b/src/ceesort.c index 9e27388..304884c 100644 --- a/src/ceesort.c +++ b/src/ceesort.c @@ -1,3 +1,4 @@ +#include "bubble.h" #include "bsrch.h" #include @@ -13,6 +14,7 @@ bool isint(char* s) if (s[i] == '-' && isdigit(s[i + 1])) continue; if (!isdigit(s[i])) return false; } + return true; } @@ -29,22 +31,52 @@ int main(int argc, char** argv) } arr[i - 1] = atoi(argv[i]); } + int n = argc - 1; - char target_str[16]; - printf("Enter number to search for: "); - scanf("%s", target_str); - while (!isint(target_str)) + char choice_str[16]; + printf( + "1. Binary search\n" + "2. Bubble sort\n" + "Please pick a mode of operation: " + ); + scanf("%s", choice_str); + // Add checking that number is in range + while (!isint(choice_str)) { - printf("Sorry but you must enter a whole number, try again: "); - scanf("%s", target_str); + printf("Sorry but you must enter a number between 1 and 2\n"); + printf("Try again: "); + scanf("%s", choice_str); } - int target = atoi(target_str); + int choice = atoi(choice_str); - int result = bsrch(target, arr, argc - 1); - if (result == -1) - puts("Value not found"); - else - printf("Value found at index: %d\n", result); + if (choice == 1) + { + char target_str[16]; + printf("Enter number to search for: "); + scanf("%s", target_str); + while (!isint(target_str)) + { + printf("Sorry but you must enter a whole number, try again: "); + scanf("%s", target_str); + } + int target = atoi(target_str); + + int result = bsrch(target, arr, n); + if (result == -1) + puts("Value not found"); + else + printf("Value found at index: %d\n", result); + } + else if (choice == 2) + { + bubblesort(arr, n); + printf("Here is your sorted list:\n"); + for (int i = 0; i < n; i++) + { + printf("%d", arr[i]); + if (i < n - 1) printf(", "); + } + } free(arr); return 0;