First, the concept: Two-point search also known as binary search, the advantage is that less than the number of times, the search speed, the average performance is good; its disadvantage is to request the table is ordered table, and insert delete difficult. Therefore, the binary lookup method is suitable for frequently ordered lists that are infrequently changed. First, suppose that the elements in the table are sorted in ascending order, compares the keywords in the middle position record of the table to the lookup key, and if the two are equal, the search succeeds; otherwise, the table is divided into the preceding and the last two child tables using the middle position record, and the previous child table is further searched if the key of the middle position record is greater than the lookup keyword Otherwise, the next child table is further searched. Repeat the process until you find a record that satisfies the criteria, make the lookup successful, or until the child table does not exist, the lookup is unsuccessful.
Second, code: for unordered arrays, use the following methods.
Header ("content-type:text/html;charset= ' Utf-8 '");
function Twosearchmethod ($arr, $val, $left, $right) {
if ($left > $right) {
echo "cannot find this value";
return;
}
$middle =round (($left + $right)/2);
if ($arr [$middle]> $val) {
Twosearchmethod ($arr, $val, $left, $middle-1);
} ElseIf ($arr [$middle]< $val) {
Twosearchmethod ($arr, $val, $middle +1, $right);
else{
echo $middle;
}
}
$arr =array (1,9,3,4,5,6,7);
Sort ($arr);
Print_r ($arr);
echo "
";
$val =1;
Twosearchmethod ($arr, $val, 0, 6);