Skip to content

Instantly share code, notes, and snippets.

@sifatshishir
Last active January 21, 2018 06:03
int binarySearch(int a[], int l, int r, int x) // recursive
{
if (r >= l)
{
int mid = l + (r - l)/2;
// If the element is present at the middle itself
if (a[mid] == x)
return mid; // return the index
// If element is smaller than mid, then
// it can only be present in left subarray
if (a[mid] > x)
return binarySearch(a, l, mid-1, x);
// Else the element can only be present
// in right subarray
return binarySearch(a, mid+1, r, x);
}
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment