php二分查找二种实现示例_PHP教程

WBOY
Release: 2016-07-13 10:36:01
Original
857 people have browsed it

php二分查找示例

二分查找常用写法有递归和非递归,在寻找中值的时候,可以用插值法代替求中值法。
当有序数组中的数据均匀递增时,采用插值方法可以将算法复杂度从中值法的lgN减小到lglgN

复制代码代码如下:

/**
* 二分查找递归解法
* @param type $subject
* @param type $start
* @param type $end
* @param type $key
* @return boolean
*/
function binarySearch_r($subject, $start, $end, $key)
{

if ( $start >= $end ) return FALSE;
$mid = getMidKey($subject, $start, $end, $key);
if ( $subject[$mid] == $key ) return $mid;
if ( $key > $subject[$mid] ) {
return binarySearch($subject, $mid, $end, $key);
}
if ( $key return binarySearch($subject, $start, $mid, $key);
}
}

/**
* 二分查找的非递归算法
* @param type $subject
* @param type $n
* @param type $key
*/
function binarySearch_nr($subject, $n, $key)
{
$low = 0;
$high = $n;
while ( $low $mid = getMidKey($subject, $low, $high, $key);
if ( $subject[$mid] == $key ) return $mid;
if ( $subject[$mid] $low = $mid + 1;
}
if ( $subject[$mid] > $key ) {
$high = $mid - 1;
}
}
}
function getMidKey($subject, $low, $high, $key)
{
/**
* 取中值算法1 取中值 不用 ($low+$high)/2的方式是因为 防止low和high较大时候,产生溢出....
*/
//return round($low + ($high - $low) / 2);

/**
* 经过改进的插值算法求中值,当数值分布均匀情况下,再降低算法复杂度到lglgN
* 取中值算法2
*/
return round( (($key - $subject[$low]) / ($subject[$high] - $subject[$low])*($high-$low) ) );
}

www.bkjia.com true http://www.bkjia.com/PHPjc/740665.html TechArticle php二分查找示例 二分查找常用写法有递归和非递归,在寻找中值的时候,可以用插值法代替求中值法。 当有序数组中的数据均匀递增时,...
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!