PHP Data structure and algorithm (PHP description) lookup and binary search _php tips

Source: Internet
Author: User
Copy Code code as follows:

<?php
/**
* Find
*
**/
Sequential Lookup
function Normal_search ($arrData, $val) {
$len = count ($arrData);
if ($len = = 0) return-1;
for ($i = 0; $i < $len; $i + +) {
echo "Find No.", $i + 1, "value =", $arrData [$i], "is =", $val, "? <br/> ";
Got it
if ($arrData [$i] = = $val) return $i;
}
return-1;
}

Test Order Lookup
$arrData = Array (4,51,6,73,2,5,9,33,50,3,4,6,1,4,67);
Echo Normal_search ($arrData, 6), "<br/>";
echo Normal_search ($arrData), "<br/>";

Binary lookup (search for ordered columns)
function Binary_search ($arrData, $val) {
$len = count ($arrData);
if ($len = = 0) return-1;

$start = 0;
$end = $len-1;

while ($start <= $end) {
$middle = Intval (($start + $end)/2);
echo "start =", $start, "end =", $end, "middle =", $middle, "<br/>";
if ($arrData [$middle] = = $val) {
return $middle;
} elseif ($arrData [$middle] > $val) {
$end = $middle-1;
} elseif ($arrData [$middle] < $val) {
$start = $middle + 1;
}
}
return-1;
}

Test the two-way search
$arrData = Array (1,2,3,4,5,7,8,9,11,23,56,100,104,578,1000);
Echo Binary_search ($arrData, 578), "<br/>";
echo Binary_search ($arrData), "<br/>";

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.