1. Concept: Binary search, also known as half search, has the advantages of less number of comparisons, fast search speed, and good average performance; its disadvantage is that the table to be looked up is required to be an ordered table, and insertion and deletion are difficult. Therefore, the binary search method is suitable for ordered lists that do not change frequently but are searched frequently. First, assuming that the elements in the table are arranged in ascending order, compare the keyword recorded in the middle position of the table with the search keyword. If the two are equal, the search is successful; otherwise, use the middle position record to divide the table into two sub-tables, the first and last. If If the keyword recorded in the middle position is greater than the search keyword, then the previous subtable will be searched further, otherwise the next subtable will be searched further. Repeat the above process until a record that meets the conditions is found, making the search successful, or until the subtable does not exist, in which case the search fails.
2. Code: For unordered arrays, use the following method.
header("Content-type:text/html;charset='utf-8'"); function twosearchmethod($arr,$val,$left,$right){ if($left>$right){ echo "找不到该数值"; 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 "<br/>"; $val=1; twosearchmethod($arr, $val, 0, 6);