Skip to content

Instantly share code, notes, and snippets.

@ahmedahamid
Created August 19, 2017 09:43
Show Gist options
  • Save ahmedahamid/606d344abb158d126eb9db71495b1d1d to your computer and use it in GitHub Desktop.
Save ahmedahamid/606d344abb158d126eb9db71495b1d1d to your computer and use it in GitHub Desktop.
Useful insights into Binary Search problems
private static int binarySearch0(int[] a, int fromIndex, int toIndex, int key) {
int low = fromIndex;
int high = toIndex - 1;
while (low <= high) {
int mid = (low + high) >>> 1;
int midVal = a[mid];
if (midVal < key)
low = mid + 1;
else if (midVal > key)
high = mid - 1;
else
return mid; // key found
}
return -(low + 1); // key not found.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment