Skip to content

Instantly share code, notes, and snippets.

@yogeshjoshi
Last active May 9, 2020 15:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yogeshjoshi/cfb69383c009bc73879959461435d14d to your computer and use it in GitHub Desktop.
Save yogeshjoshi/cfb69383c009bc73879959461435d14d to your computer and use it in GitHub Desktop.
public static int binarySearch(int[] a, int key) {
int low = 0;
int high = a.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
int midVal = a[mid];
if (midVal < key)
low = mid + 1
else if (midVal > key)
high = mid - 1;
else
return mid; // Key has found
}
return -1; // key not found.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment