Last active
January 21, 2018 06:03
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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