Skip to content

Instantly share code, notes, and snippets.

@zigo928
Created October 22, 2014 09:40
Show Gist options
  • Save zigo928/18431a1bccb197082580 to your computer and use it in GitHub Desktop.
Save zigo928/18431a1bccb197082580 to your computer and use it in GitHub Desktop.
二分查找实现
<?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