Created
April 13, 2012 20:41
-
-
Save 0x1b-xyz/2380027 to your computer and use it in GitHub Desktop.
Some binary searching
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
/** | |
* 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