Home > Backend Development > PHP Tutorial > Binary PHP array binary search function code

Binary PHP array binary search function code

WBOY
Release: 2016-07-29 08:41:56
Original
972 people have browsed it

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.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template