Skip to content

Instantly share code, notes, and snippets.

@shailrshah
Last active October 11, 2017 13:14
Show Gist options
  • Save shailrshah/f45c1f7cc04f2434637dd9928a4e1ef8 to your computer and use it in GitHub Desktop.
Save shailrshah/f45c1f7cc04f2434637dd9928a4e1ef8 to your computer and use it in GitHub Desktop.
Binary Search
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