Home > Backend Development > PHP Tutorial > PHP array binary search function code_PHP tutorial

PHP array binary search function code_PHP tutorial

WBOY
Release: 2016-07-21 15:40:59
Original
924 people have browsed it

Copy code The code is as follows:

//search function where $array is the array and $k is the desired The value to be found, $low is the minimum key value of the search range, $high is the maximum key value of the search range
function search($array, $k, $low=0, $high=0)
{
if(count($array)!=0 and $high == 0) //Determine whether this is the first call
{
$high = count($array);
}
if($low <= $high) //If there are remaining array elements
{
$mid = intval(($low+$high)/2); //Take $low and $high The middle value of 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 the search function
echo search($array, 8); //Call the search function and output the search results
?>





http://www.bkjia.com/PHPjc/321261.html
www.bkjia.com

truehttp: //www.bkjia.com/PHPjc/321261.htmlTechArticleCopy the code as follows: ?php //search function where $array is the array and $k is the value to be found , $low is the minimum key value of the search range, $high is the maximum key value of the search range function search(...
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