The basic idea of binary search is to compare the middle value of an ordered array with the value you are looking for. When the value you are looking for is greater than the middle value of the array, it means all the values before the middle value of the ordered array. are all less than the value to be searched, so you can exclude all values before the middle value of the array, and then continue to search for the required value from the middle value of the array to the value at the end of the array. The code is implemented as follows:
//Binary search
function bin_search($array,$search){
$low=0;
$height=count($array)-1;//Get Array length
while($low<=$height){
$mid=floor(($low+$height)/2);//Get the middle number and cast it to floor type, Prevent errors
if($array[$mid]==$search){
return $mid+1;//Return the found serial number
}else if($array[ $mid]<$search){
//When the middle value is less than the checked value, the values to the left of $mid are all less than $search. At this time, $mid should be assigned to $low
$ low=$mid+1;
}else if($array[$mid]>$search){
//At this time, it means that the middle value is greater than the checked value, then all the values to the right of $mid are is greater than $search, at this time $mid should be assigned to $height
$height=$mid-1;
}
return "Search failed";//The search failed, the item does not exist in the array Value
}
}
$arr=array(1,4,6,33,75,88,89,93);
echo bin_search($arr, 33);
echo bin_search($arr,66);
?>
The above introduces the PHP data structure (1) binary search, including the content. I hope it will be helpful to friends who are interested in PHP tutorials.