Copy the code The code is as follows:
//search function where $array is the array, $k is the value to be found, $low is the minimum key value of the search range, and $high is the search function The maximum key value of the range
function search($array, $k, $low=0, $high=0)
{
if(count($array)!=0 and $high == 0) //Determine whether it is First call
{
$high = count($array);
}
if($low <= $high) //If there are remaining array elements
{
$mid = intval(($low+$ high)/2); //Take the middle value between $low and $high
if ($array[$mid] == $k) //If found, return
{
return $mid;
}
elseif ($ k < $array[$mid]) //If not found, continue searching
{
return search($array, $k, $low, $mid-1);
}
else
{
return search( $array, $k, $mid+1, $high);
}
}
return -1;
}
$array = array(4,5,7,8,9,10); //Test search function
echo search($array, 8); //Call the search function and output the search results
?>
The above introduces the bisection PHP array binary search function code, including the content of the bisection method. I hope it will be helpful to friends who are interested in PHP tutorials.