Home > php教程 > php手册 > php 二分查找法算法详解

php 二分查找法算法详解

WBOY
Release: 2016-06-13 09:27:35
Original
1414 people have browsed it

php 二分查找法算法详解

一、概念:二分查找又称折半查找,优点是比较次数少,查找速度快,平均性能好;其缺点是要求待查表为有序表,且插入删除困难。因此,折半查找方法适用于不经常变动而查找频繁的有序列表。首先,假设表中元素是按升序排列,将表中间位置记录的关键字与查找关键字比较,如果两者相等,则查找成功;否则利用中间位置记录将表分成前、后两个子表,如果中间位置记录的关键字大于查找关键字,则进一步查找前一子表,否则进一步查找后一子表。重复以上过程,直到找到满足条件的记录,使查找成功,或直到子表不存在为止,此时查找不成功。

二、代码:对于无序数组用以下方法即可。

header("Content-type:text/html;charset='utf-8'");
function twosearchmethod($arr,$val,$left,$right){
	if($left>$right){
		echo "找不到该数值";
		return ;
	}
	$middle=round(($left+$right)/2);
	if($arr[$middle]>$val){
		twosearchmethod($arr, $val, $left, $middle-1);
	}elseif($arr[$middle]<$val){
		twosearchmethod($arr, $val, $middle+1, $right);
	}else{
		echo $middle;
	}
	
}
$arr=array(1,9,3,4,5,6,7);
sort($arr);
print_r($arr);
echo "<br/>";
$val=1;
twosearchmethod($arr, $val, 0, 6);
Copy after login

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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template