Created
June 1, 2015 03:32
-
-
Save firomero/b8b0a52ff8859fa1c79f to your computer and use it in GitHub Desktop.
BinarySearch
This file contains 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
<?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