From 2de3cd2df05105ed45281f6496244f3b9706c407 Mon Sep 17 00:00:00 2001 From: Mohammad Sahil <144834170+mdsahilnoob@users.noreply.github.com> Date: Fri, 22 Dec 2023 00:04:46 +0530 Subject: [PATCH] Create binary_search.c --- binary_search.c | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 binary_search.c diff --git a/binary_search.c b/binary_search.c new file mode 100644 index 0000000..75d1f96 --- /dev/null +++ b/binary_search.c @@ -0,0 +1,37 @@ +#include + +int binarySearch(int arr[], int left, int right, int target) { + while (left <= right) { + int mid = left + (right - left) / 2; + + // Check if the target is present at the middle + if (arr[mid] == target) + return mid; + + // If the target is greater, ignore the left half + if (arr[mid] < target) + left = mid + 1; + + // If the target is smaller, ignore the right half + else + right = mid - 1; + } + + // If the target is not present in the array + return -1; +} + +int main() { + int arr[] = {2, 3, 4, 10, 40}; + int n = sizeof(arr) / sizeof(arr[0]); + int target = 10; + + int result = binarySearch(arr, 0, n - 1, target); + + if (result == -1) + printf("Element is not present in array\n"); + else + printf("Element is present at index %d\n", result); + + return 0; +}