Skip to content

Instantly share code, notes, and snippets.

@emmettna
Created January 31, 2017 05:50
Show Gist options
  • Save emmettna/b7d76f68aa52767d3260ef4588868a9d to your computer and use it in GitHub Desktop.
Save emmettna/b7d76f68aa52767d3260ef4588868a9d to your computer and use it in GitHub Desktop.
public static int rank(int key, int[] a){
// Array must be sorted.
int lo = 0;
int hi = a.length - 1;
while (lo <= hi){
// Key is in a[lo..hi] or not present.
int mid = lo + (hi - lo) / 2;
if (key < a[mid]) hi = mid - 1;
else if (key > a[mid]) lo = mid + 1;
else return mid;
}
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment