凌的博客

您现在的位置是: 首页 > 学无止境 > PHP > 

PHP

二分法查找

2016-01-25 PHP 354
header(\'Content-Type: text/html; charset=utf-8;\'); $arr = array(2,33,22,1,323,321,28,36,90,123); sort($arr); //二分法查找 echo $index = binarySearch($arr,321); function binarySearch($arr,$
	header('Content-Type: text/html; charset=utf-8;');

	$arr = array(2,33,22,1,323,321,28,36,90,123);
	sort($arr);

	//二分法查找
	echo $index = binarySearch($arr,321);
	
	function binarySearch($arr,$key){
		$len = count($arr);
		$mid = -1;
		$start = 0;
		$end   = $len-1;

		while($start<=$end){
			$mid = (int)(($start+$end)/2);
			echo $mid."\n";
			if($arr[$mid] == $key){
				return $mid;
			}else if($arr[$mid] < $key){
				$start = $mid+1;
			}else if($arr[$mid] > $key){
				$end = $mid-1;	
			}
		}
	}

文章评论

0条评论