Last active
October 11, 2017 13:14
-
-
Save shailrshah/f45c1f7cc04f2434637dd9928a4e1ef8 to your computer and use it in GitHub Desktop.
Binary Search
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
static int binarySearchIterative(int[] a, int key) { | |
int low = 0; | |
int high = a.length - 1; | |
while(low <= high) { | |
int mid = (low + high) / 2; | |
if(key == a[mid]) | |
return mid; | |
else if (key < a[mid]) | |
high = mid -1; | |
else if (key > a[mid]) | |
low = mid + 1; | |
} | |
return -1; | |
} | |
static int binarySearchRecursive(int[] a, int key, int low, int high) { | |
if(low > high) | |
return -1; | |
int mid = (low + high) / 2; | |
if(key == a[mid]) | |
return mid; | |
else if (key < a[mid]) | |
return binarySearchRecursive(a, key, low, mid - 1); | |
else | |
return binarySearchRecursive(a, key, mid + 1, high); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment