From 2c9ce86b76676f76cedaf6d1b66276f3153b4fb4 Mon Sep 17 00:00:00 2001 From: Roland W-H Date: Sun, 29 May 2022 20:01:58 +0100 Subject: [PATCH] added linear search --- src/ceesort.c | 18 +++++++++++++++--- src/lsrch.c | 17 +++++++++++++++++ src/lsrch.h | 12 ++++++++++++ 3 files changed, 44 insertions(+), 3 deletions(-) create mode 100644 src/lsrch.c create mode 100644 src/lsrch.h diff --git a/src/ceesort.c b/src/ceesort.c index 5d67f7a..4430d40 100644 --- a/src/ceesort.c +++ b/src/ceesort.c @@ -7,6 +7,7 @@ #include "bubble.h" #include "bsrch.h" +#include "lsrch.h" #include "ccolour/colour.h" #include @@ -16,7 +17,7 @@ #include -inline void quit_err(const char* msg) +static inline void quit_err(const char* msg) { ChangeColour(msg, RED_FOREGROUND, DEFAULT_COLOR, true); exit(EXIT_FAILURE); @@ -62,6 +63,7 @@ int main(int argc, char** argv) printf( "1. Binary search\n" "2. Bubble sort\n" + "3. Liniar search\n" "Please pick a mode of operation: " ); fgets(choice_str, 16, stdin); @@ -70,7 +72,7 @@ int main(int argc, char** argv) // TODO: Add checking that number is in range while (!isint(choice_str)) { - printf("Sorry but you must enter a number between 1 and 2\n"); + printf("Sorry but you must enter a number between 1 and 3\n"); printf("Try again: "); fgets(choice_str, 16, stdin); choice_str[strcspn(choice_str, "\n")] = 0; @@ -108,7 +110,17 @@ int main(int argc, char** argv) } putchar('\n'); } - + else if (choice == 3) + { + char target_str[16]; + printf("Enter number to search for: "); + fgets(target_str, 16, stdin); target_str[strcspn(target_str, "\n")] = 0; + while (!isint(target_str)) + { printf("Sorry but you must enter a whole number, try again: "); fgets(target_str, 16, stdin); + } + int target = atoi(target_str); int result = lsrch(arr, n, target); if (result == -1) puts("Value not found"); else printf("Value found at index: %d\n", result); + } + free(arr); return 0; } diff --git a/src/lsrch.c b/src/lsrch.c new file mode 100644 index 0000000..80d2f1d --- /dev/null +++ b/src/lsrch.c @@ -0,0 +1,17 @@ +/* + * Filename: lsrch.c + * Author(s): Roland (r.weirhowell@gmail.com) + * Description: Perform linear search on an integer array + * License: MIT (https://spdx.org/licenses/MIT.html) +*/ + +#include "lsrch.h" + +int lsrch(int* arr, int n, int target) +{ + for (int i = 0; i < n; i++) + if (arr[i] == target) return i; + + return -1; +} + diff --git a/src/lsrch.h b/src/lsrch.h new file mode 100644 index 0000000..3cd5980 --- /dev/null +++ b/src/lsrch.h @@ -0,0 +1,12 @@ +/* + * Filename: lsrch.h + * Author(s): Roland (r.weirhowell@gmail.com) + * Description: Header file for lsrch.c + * License: MIT (https://spdx.org/licenses/MIT.html) +*/ + +#pragma once + + +int lsrch(int* arr, int n, int target); +