Created
October 22, 2014 09:40
-
-
Save zigo928/18431a1bccb197082580 to your computer and use it in GitHub Desktop.
二分查找实现
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
<?php | |
/** | |
* 二分查找 | |
* | |
* @param $a array | |
* @param $v 查找的值 | |
* | |
* @return int | |
*/ | |
function binarySearch($a, $v) | |
{ | |
assert("is_array($a)"); | |
assert("is_string('$v')"); | |
sort($a); | |
$left = 0; | |
$right = count($a) - 1; | |
while ($left <= $right) { | |
$middle = $left + (($right - $left) >> 1); | |
if ($a[$middle] > $v) { | |
$right = $middle - 1; | |
} elseif ($a[$middle] < $v) { | |
$left = $middle + 1; | |
} else { | |
return $middle; | |
} | |
} | |
return -1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment