Created
August 19, 2017 09:43
-
-
Save ahmedahamid/606d344abb158d126eb9db71495b1d1d to your computer and use it in GitHub Desktop.
Useful insights into Binary Search problems
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
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