<?php
//recursive variant
function searchBin($arr, $lo, $hi, $search) {
if($lo <= $hi) {
$m = ($lo + $hi) >> 1;
if($arr[ $m ] == $search) return($m);
else if($arr[$m] > $search) {
return searchBin($arr, $lo, $m - 1, $search);
} else {
return searchBin($arr, $m + 1, $hi, $search);
}
}
return -1;
}
//recursive variant
function searchBin2($arr, $lo, $hi, $search) {
if($lo > $hi) return -1;
$m = ($lo + $hi) >> 1;
if($arr[ $m ] == $search) return($m);
else if($arr[$m] > $search) {
return searchBin($arr, $lo, $m - 1, $search);
} else {
return searchBin($arr, $m + 1, $hi, $search);
}
}
//iterative solution
function binSearch($arr, $lo, $hi, $search) {
$pos = -1;
while($lo <= $hi) {
$m = ($lo + $hi) >> 1;
if($arr[$m] == $search) {
$pos = $m;
break;
} else if($arr[$m] > $search) {
$hi = $m - 1;
} else {
$lo = $m + 1;
}
}
return $pos;
}
$arr = array(-9,-3,-1,10,87,88,118,180,280,480,580,780);
$search = 87;
$pos = binsearch($arr, 0, $n - 1, $search);
echo"Search: ". $search;
echo" Finding at position: ". $pos;
?>
PD9waHAKCi8vcmVjdXJzaXZlIHZhcmlhbnQKZnVuY3Rpb24gc2VhcmNoQmluKCRhcnIsICRsbywgJGhpLCAkc2VhcmNoKSB7CgogICAgICAgICBpZigkbG8gPD0gJGhpKSB7CgogICAgICAgICAgICAkbSA9ICgkbG8gKyAkaGkpID4+IDE7CgogICAgICAgICAgICBpZigkYXJyWyAkbSBdID09ICRzZWFyY2gpIHJldHVybigkbSk7CgogICAgICAgICAgICBlbHNlIGlmKCRhcnJbJG1dID4gJHNlYXJjaCkgewoKICAgICAgICAgICAgICAgICAgcmV0dXJuIHNlYXJjaEJpbigkYXJyLCAkbG8sICRtIC0gMSwgJHNlYXJjaCk7CiAgICAgICAgICAgIH0gZWxzZSB7CgogICAgICAgICAgICAgICAgICByZXR1cm4gc2VhcmNoQmluKCRhcnIsICRtICsgMSwgJGhpLCAkc2VhcmNoKTsKICAgICAgICAgICAgfQoKICAgICAgICAgfQogICAgICAgICByZXR1cm4gLTE7Cn0KCgovL3JlY3Vyc2l2ZSB2YXJpYW50CmZ1bmN0aW9uIHNlYXJjaEJpbjIoJGFyciwgJGxvLCAkaGksICRzZWFyY2gpIHsKCiAgICAgICAgIGlmKCRsbyA+ICRoaSkgcmV0dXJuIC0xOwoKICAgICAgICAgICAgJG0gPSAoJGxvICsgJGhpKSA+PiAxOwoKICAgICAgICAgICAgaWYoJGFyclsgJG0gXSA9PSAkc2VhcmNoKSByZXR1cm4oJG0pOwoKICAgICAgICAgICAgZWxzZSBpZigkYXJyWyRtXSA+ICRzZWFyY2gpIHsKCiAgICAgICAgICAgICAgICAgIHJldHVybiBzZWFyY2hCaW4oJGFyciwgJGxvLCAkbSAtIDEsICRzZWFyY2gpOwogICAgICAgICAgICB9IGVsc2UgewoKICAgICAgICAgICAgICAgICAgcmV0dXJuIHNlYXJjaEJpbigkYXJyLCAkbSArIDEsICRoaSwgJHNlYXJjaCk7CiAgICAgICAgICAgIH0KfQoKLy9pdGVyYXRpdmUgc29sdXRpb24KZnVuY3Rpb24gYmluU2VhcmNoKCRhcnIsICRsbywgJGhpLCAkc2VhcmNoKSB7CiAgICAgICAgICRwb3MgPSAtMTsKCiAgICAgICAgIHdoaWxlKCRsbyA8PSAkaGkpIHsKCiAgICAgICAgICAgICAgICRtID0gKCRsbyArICRoaSkgPj4gMTsKICAgICAgICAgICAgICAgaWYoJGFyclskbV0gPT0gJHNlYXJjaCkgewogICAgICAgICAgICAgICAgICAkcG9zID0gJG07CiAgICAgICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICAgICB9IGVsc2UgaWYoJGFyclskbV0gPiAkc2VhcmNoKSB7CiAgICAgICAgICAgICAgICAgICRoaSA9ICRtIC0gMTsKICAgICAgICAgICAgICAgfSBlbHNlIHsKICAgICAgICAgICAgICAgICAgJGxvID0gJG0gKyAxOwogICAgICAgICAgICAgICB9CiAgICAgICAgIH0KICAgICAgICAgcmV0dXJuICRwb3M7Cn0KCiRhcnIgPSBhcnJheSgtOSwtMywtMSwxMCw4Nyw4OCwxMTgsMTgwLDI4MCw0ODAsNTgwLDc4MCk7CgoKJG4gPSBzaXplb2YoJGFycik7Cgokc2VhcmNoID0gODc7CgokcG9zID0gYmluc2VhcmNoKCRhcnIsIDAsICRuIC0gMSwgJHNlYXJjaCk7CgplY2hvIlNlYXJjaDogIi4gJHNlYXJjaDsKCmVjaG8iIEZpbmRpbmcgYXQgcG9zaXRpb246ICIuICRwb3M7Cgo/Pg==