Skip to content

Instantly share code, notes, and snippets.

@0x1b-xyz
Created April 13, 2012 20:41
Show Gist options
  • Save 0x1b-xyz/2380027 to your computer and use it in GitHub Desktop.
Save 0x1b-xyz/2380027 to your computer and use it in GitHub Desktop.
Some binary searching
/**
* search the (sorted) array for the indicated value
*
* @return index of the value or -1 when not found.
*/
def search(arr, int val) {
int min = 0
int max = arr.size() - 1
while (max > min) {
int piv = Math.abs((min + max) / 2)
if (arr[piv] == val) return piv
if (arr[piv] > val) max = piv
else min = piv
if (piv == 0) break;
}
return -1
}
assert search([5, 34, 42, 54, 63, 72, 89, 91, 121], 89) == 6
assert search([5, 34, 42, 54, 63, 72, 89, 91, 121], 32) == -1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment