From 193bee0930a9fd4270cf79c5834ad018dc6a3843 Mon Sep 17 00:00:00 2001 From: aryan raj Date: Thu, 9 Sep 2021 21:35:57 -0700 Subject: [PATCH] added binary search algo in c++ --- c++/binarysearch2.cpp | 50 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 c++/binarysearch2.cpp diff --git a/c++/binarysearch2.cpp b/c++/binarysearch2.cpp new file mode 100644 index 0000000..927a4e5 --- /dev/null +++ b/c++/binarysearch2.cpp @@ -0,0 +1,50 @@ +#include +using namespace std; + +int binarySearch(int arr[], int l , int r, int num); + +int main() +{ + int n, num; + cin >> n >> num; + int arr[n]; + for (int i = 0; i < n; i++) + { + cin >> arr[i]; + } + + int index = binarySearch(arr, 0, n - 1, num); + if (index == -1) + { + cout << num << " is not present in the given array"; + } + + else + { + cout << num << " is present at index " << index + 1 << " in the array"; + } + + return 0; +} +int binarySearch(int arr[], int l, int r, int num) +{ + if (l <= r) + { + int mid = l + (r-1)/2; + if (arr[mid] == num) + { + return mid; + } + + if (arr[mid] > num) + { + return binarySearch(arr, l, mid - 1, num); + } + + if (arr[mid] < num) + { + return binarySearch(arr, mid + 1, r, num); + } + } + return -1; +}