From e24eeb5fd2945cdeeffd1ae0e1fd88dd7a105c4d Mon Sep 17 00:00:00 2001 From: adhilcodes Date: Wed, 14 Oct 2020 10:25:20 +0530 Subject: [PATCH] adding c++ program file --- Binary_search/main.cpp | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Binary_search/main.cpp diff --git a/Binary_search/main.cpp b/Binary_search/main.cpp new file mode 100644 index 0000000..354ea15 --- /dev/null +++ b/Binary_search/main.cpp @@ -0,0 +1,26 @@ +#include +using namespace std; +int binarySearch(int arr[], int l, int r, int x) +{ + if (r >= l) + { + int mid = l + (r - l) / 2; + if (arr[mid] == x) + return mid; + if (arr[mid] > x) + return binarySearch(arr, l, mid - 1, x); + return binarySearch(arr, mid + 1, r, x); + } + return -1; +} + +int main(void) +{ + int arr[] = { 24, 33, 4, 130, 41 }; + int x = 4; + int n = sizeof(arr) / sizeof(arr[0]); + int result = binarySearch(arr, 0, n - 1, x); + (result == -1) ? cout << "No such Element in array" + : cout << "Element is present at index " << result; + return 0; +} \ No newline at end of file