What's wrong with writing two-point lookups?
function BinarySearch ($arr, $a) {
$low = 0;
$high = count ($arr)-1;
$mid = Ceil (($low + $high)/2);
while ($low <= $high) {
if ($a = = $arr [$mid]) {
echo "The location of the number to find is". " $mid ";
}
if ($a > $arr [$mid]) {
$high = count ($arr)-1;
$low = $mid +1;
$mid = Ceil (($low + $high)/2);
}
if ($a < $arr [$mid]) {
$low = 0;
$high = $mid-1;
$mid = Ceil (($low + $high)/2);
}
}
}
$arr 1 = array (5,7,9,10,12,16,19);
BinarySearch ($arr 1,12);
?>
------Solution--------------------
This post was last edited by xuzuning on 2013-03-30 17:42:33
function BinarySearch ($arr, $a) {
$low = 0;
$high = count ($arr)-1;
$mid = Ceil (($low + $high)/2);
$n = 0;Measures to prevent the death cycle
while ($low <= $high && $n + + ){
if ($a = = $arr [$mid]) {
echo "The location of the number to find is". " $mid ";
Break
}
if ($a > $arr [$mid]) {
$high = count ($arr)-1;
$low = $mid -1; //Note here
$mid = Ceil (($low + $high)/2);
}
if ($a < $arr [$mid]) {
$low = 0;
$high = $mid +1; //Note here
$mid = Ceil (($low + $high)/2);
}
}
}
------Solution--------------------
By PHP actually can write
function BinarySearch ($arr, $a) {
$low = 0;
$high = count ($arr)-1;
$mid = Ceil (($low + $high)/2);
$num = count ($arr);
while ($low <= $high && $num-) {
if ($a = = $arr [$mid]) {
echo "The location of the number to find is". " $mid ";
Break
}
List ($low, $high) = $a > $arr [$mid]? Array ($mid, $high): Array ($low, $mid);
$mid = Ceil (($low + $high)/2);
}
}
------Solution--------------------