diff --git a/CPP/Trees/Binary.cpp b/CPP/Trees/Binary.cpp new file mode 100644 index 00000000..8645716a --- /dev/null +++ b/CPP/Trees/Binary.cpp @@ -0,0 +1,39 @@ +#include +using namespace std; + +// A recursive binary search function. It returns +// location of x in given array arr[low..high] is present, +// otherwise -1 +int binarySearch(int arr[], int low, int high, int x) +{ + if (high >= low) { + int mid = low + (high - low) / 2; + + // If the element is present at the middle + // itself + if (arr[mid] == x) + return mid; + + // If element is smaller than mid, then + // it can only be present in left subarray + if (arr[mid] > x) + return binarySearch(arr, low, mid - 1, x); + + // Else the element can only be present + // in right subarray + return binarySearch(arr, mid + 1, high, x); + } + return -1; +} + +// Driver code +int main() +{ + int arr[] = { 2, 3, 4, 10, 40 }; + int query = 90; + int n = sizeof(arr) / sizeof(arr[0]); + int result = binarySearch(arr, 0, n - 1, query); + if (result == -1) cout << "Element is not present in array"; + else cout << "Element is present at index " << result; + return 0; +}