From 159c720e49ca73c008bcd8c22000c93a804c0aff Mon Sep 17 00:00:00 2001 From: baz Date: Wed, 21 Feb 2024 01:40:45 +0000 Subject: [PATCH] Implement Binary Search --- binarysearch/main.c | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 binarysearch/main.c diff --git a/binarysearch/main.c b/binarysearch/main.c new file mode 100644 index 0000000..ad1ca46 --- /dev/null +++ b/binarysearch/main.c @@ -0,0 +1,33 @@ +#include + +int main(int argc, char *argv[]) +{ + int arr[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19}; + + int low = 0; + int high = (sizeof(arr) / sizeof(arr[0])) - 1; + int mid = 0; + int searchterm = 6; + + while (low < high) + { + mid = low + ((high - low) / 2); + + if (searchterm == arr[mid]) + { + printf("%d", mid); + return 1; + } + else if (searchterm > arr[mid]) + { + low = mid + 1; + } + else + { + high = mid; + } + } + + printf("No value found"); + return 0; +} \ No newline at end of file