Copy CodeThe code is as follows:
The search function, where $array is an array, $k the value to find, $low the minimum key value for the lookup range, $high the maximum key value for the lookup range
function Search ($array, $k, $low =0, $high =0)
{
if (count ($array)!=0 and $high = = 0)//Determine if the call is the first time
{
$high = count ($array);
}
if ($low <= $high)//If there are remaining array elements
{
$mid = Intval (($low + $high)/2); Take the middle value of $low and $high
if ($array [$mid] = = $k)//return if found
{
return $mid;
}
ElseIf ($k < $array [$mid]//If not found, continue to find
{
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 the search function
Echo Search ($array, 8); Call the search function and output the lookup results
?>
http://www.bkjia.com/PHPjc/321261.html www.bkjia.com true http://www.bkjia.com/PHPjc/321261.html techarticle Copy the code as follows:? PHP//search function where $array is an array, $k is the value to find, $low to find the minimum key value for the range, $high the maximum key value for the lookup range function search (... ).