Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions CPP/Trees/Binary.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
#include <bits/stdc++.h>
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;
}