算法学习系列 -- 二分查找

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/ydm19891101/article/details/97616113

二分查找可以说是最常见的查找了,再加上最近在系统梳理算法相关的内容,本着实践大于理论的原则,争取对于常见的算法都手动撸一遍。

OK,废话少说,直接上PHP版本的二分查找算法。

如果元素不存在,下面的算法会返回元素会被插入的位置。

<?php 

//对于二分查找算法而言,要求数据是有序的O(logn)
//而对于二叉查找树而言(logn),要求数据是无序的,否则就会退化为顺序查找O(n)
function searchInsert($nums, $target) {
	$minIndex = 0;
	$maxIndex = count($nums) - 1;
	
	if ($target < $nums[0]) {
		return 0;
	}
	if ($target > $nums[$maxIndex]) {
		return $maxIndex + 1;
	}
	
	//二分查找
	while($minIndex <= $maxIndex) {
		$midIndex = ($maxIndex + $minIndex) >>1;
		if ($nums[$midIndex] == $target) {
			return $midIndex;
		} else if ($nums[$midIndex] > $target) {
			$maxIndex = $midIndex - 1;
		} else {
			$minIndex = $midIndex + 1;
		}
	}
	
	return $minIndex;
}

$nums = array(1,3,5,6);
$res = searchInsert($nums, 2);
echo 'the position of the element is:' . $res;

这里,有以下几个需要特殊注意的点:

  • 为了避免两个整数相加越界,一定要使用left + (right - left) /2 或者 右移来获取中间位置的索引值;建议使用右移,因为右移的效率更高
  • 当中间值不满足要求时,对于left / right进行加减一操作
  • 该算法的运用要求元素是有序的

猜你喜欢

转载自blog.csdn.net/ydm19891101/article/details/97616113