Blog

It's a Wonderful Life

二分查找算法

2017-03-02 17:47 Posted in Learn with PHP , algorithm

二分查找也是一道经典面试题。。现在贴上两种实现方法(递归和非递归)。

首先是非递归式的算法:

<?php
function binsearch($arr, $val)
{
	$len = count($arr);
	$low = 0;
	$high = $len - 1;
	
	//if $val is greater than the greatest value or small than the smallest value in that array, don't bother to search.
	if ($val < $arr[$low] || $val > $arr[$high])
	{
		return "$val is not found";
	}
	
	while ($low <= $high)
	{
		$mid = round(($low + $high) / 2);
		
		if ($arr[$mid] < $val)
		{
			$low = $mid + 1;
		}
		else if ($arr[$mid] > $val)
		{
			$high = $mid - 1;
		}
		else
		{
			return $mid;
		}
	}
	
	//not found
	return "$val not in that array";
}

下面是递归式的实现方法:

<?php
function binsearch($arr, $val, $low, $high)
{
	
	if ($val < $arr[$low] || $val > $arr[$high])
	{
		return "$val is not found";
	}
	
	if ($low <= $high)
	{
		$mid = round(($low + $high) / 2);
		
		if ($arr[$mid] == $val)
		{
			return $mid;
		}
		else if ($arr[$mid] > $val)
		{
			return binsearch($arr, $val, $low, $mid - 1);
		}
		else if ($arr[$mid] < $val)
		{
			return binsearch($arr, $val, $mid + 1, $high);
		}
	}
	else
	{
		return "$val is not found";
	}
	
}