From deb439fc611ce5703bae46106adc7dcca1607b02 Mon Sep 17 00:00:00 2001 From: anishhh238 <115490102+anishhh238@users.noreply.github.com> Date: Thu, 27 Oct 2022 21:31:08 +0530 Subject: [PATCH] Created C++ program of Binary Search --- binary_search.cpp | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 binary_search.cpp diff --git a/binary_search.cpp b/binary_search.cpp new file mode 100644 index 0000000..b94f31c --- /dev/null +++ b/binary_search.cpp @@ -0,0 +1,34 @@ +// Binary Search in C++ + +#include +using namespace std; + +int binarySearch(int array[], int x, int low, int high) { + + // Repeat until the pointers low and high meet each other + while (low <= high) { + int mid = low + (high - low) / 2; + + if (array[mid] == x) + return mid; + + if (array[mid] < x) + low = mid + 1; + + else + high = mid - 1; + } + + return -1; +} + +int main(void) { + int array[] = {3, 4, 5, 6, 7, 8, 9}; + int x = 4; + int n = sizeof(array) / sizeof(array[0]); + int result = binarySearch(array, x, 0, n - 1); + if (result == -1) + printf("Not found"); + else + printf("Element is found at index %d", result); +}