From a1477bc584df1b90a0ef09d4694052121f504765 Mon Sep 17 00:00:00 2001 From: ishita707 <88577359+Ishitamodi03@users.noreply.github.com> Date: Sun, 23 Oct 2022 12:14:15 +0530 Subject: [PATCH] binary search using iterative method. --- binary_search.cpp | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 binary_search.cpp diff --git a/binary_search.cpp b/binary_search.cpp new file mode 100644 index 0000000..778ef2d --- /dev/null +++ b/binary_search.cpp @@ -0,0 +1,31 @@ +#include +using namespace std; + +int binarySearch(int array[], int x, int low, int high) { + + 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[] = {2, 3, 4, 5, 6, 7, 8}; + int x = 3; + 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); +}