Skip to content

Instantly share code, notes, and snippets.

@firomero
Created June 1, 2015 03:32
Show Gist options
  • Save firomero/b8b0a52ff8859fa1c79f to your computer and use it in GitHub Desktop.
Save firomero/b8b0a52ff8859fa1c79f to your computer and use it in GitHub Desktop.
BinarySearch
<?php
/*
* Parameters:
* $a - The sort array.
* $first - First index of the array to be searched (inclusive).
* $last - Last index of the array to be searched (exclusive).
* $key - The key to be searched for.
* $compare - A user defined function for comparison. Same definition as the one in usort
*
* Return:
* index of the search key if found, otherwise return (-insert_index - 1).
* insert_index is the index of smallest element that is greater than $key or sizeof($a) if $key
* is larger than all elements in the array.
*/
function binary_search(array $a, $first, $last, $key, $compare) {
$lo = $first;
$hi = $last - 1;
while ($lo <= $hi) {
$mid = (int)(($hi - $lo) / 2) + $lo;
$cmp = call_user_func($compare, $a[$mid], $key);
if ($cmp < 0) {
$lo = $mid + 1;
} elseif ($cmp > 0) {
$hi = $mid - 1;
} else {
return $mid;
}
}
return -($lo + 1);
}
function cmp($a, $b) {
return ($a < $b) ? -1 : (($a > $b) ? 1 : 0);
}
$a = array(1,2,3,4,5,6);
$idx = binary_search($a, 0, sizeof($a), 4, 'cmp');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment