From 2efd5b1ff1849a14e361c3bea009ffee9dc240c6 Mon Sep 17 00:00:00 2001 From: Rishika Snehi <140375965+rishikasnehi@users.noreply.github.com> Date: Tue, 24 Oct 2023 11:55:28 +0530 Subject: [PATCH 1/2] Adding C implementation of binary search algorithm --- Searching Algorithms/Binary Search/Binary_Search.c | 1 + 1 file changed, 1 insertion(+) create mode 100644 Searching Algorithms/Binary Search/Binary_Search.c diff --git a/Searching Algorithms/Binary Search/Binary_Search.c b/Searching Algorithms/Binary Search/Binary_Search.c new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/Searching Algorithms/Binary Search/Binary_Search.c @@ -0,0 +1 @@ + From bc5809cb3ff2c9d9de81e3824c287823d639a4fa Mon Sep 17 00:00:00 2001 From: Rishika Snehi <140375965+rishikasnehi@users.noreply.github.com> Date: Tue, 24 Oct 2023 12:12:08 +0530 Subject: [PATCH 2/2] Added binary search implementation --- .../Binary Search/Binary_Search.c | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/Searching Algorithms/Binary Search/Binary_Search.c b/Searching Algorithms/Binary Search/Binary_Search.c index 8b13789..8c234f2 100644 --- a/Searching Algorithms/Binary Search/Binary_Search.c +++ b/Searching Algorithms/Binary Search/Binary_Search.c @@ -1 +1,64 @@ +// Detail: Program for searching an element in the integer array using binary search +// Author: Rishika Snehi +// Note: Uncomment print statements for debugging or understanding the flow +#include + +int binarySearch(int arr[], int target, int arr_len) +{ + // initialize start & end + int start = 0; + int end = arr_len - 1; + + // loop start start pointer is before end pointer + while (start <= end) + { + // find mid element + // using int overflow safe formula for computing middle index + int mid = start + ((end - start) / 2); + // printf("mid: %d\n", mid); + + // compare mid element with target integer + if (arr[mid] == target) + { + return mid; + } + else if (arr[mid] > target) // target is in first half of the array + { + end = mid - 1; + // printf("start = %d end =%d\n", start, end); + } + else // target is in later half of the array + { + start = mid + 1; + // printf("start = %d end =%d\n", start, end); + } + } + + // if we reached here, then it means that element was not found + return -1; +} + +int main() +{ + int arr[10] = {1, 12, 23, 34, 45, 56, 67, 78, 89, 90}; + int target; + + printf("input array: "); + for (int i = 0; i < 10; i++) + { + printf("%d ", arr[i]); + } + printf("\n"); + + printf("Enter the target number you want to search: "); + scanf("%d", &target); + + int arr_len = sizeof(arr) / sizeof(arr[0]); + + int pos = binarySearch(arr, target, arr_len); + if (pos != -1) + printf("The target number is present in array at %dth position", pos); + else + printf("element not found in the array\n"); +}