How is it wrong to write two-point lookups?

Source: Internet
Author: User
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--------------------
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.