Home  >  Article  >  php教程  >  php二分法

php二分法

PHP中文网
PHP中文网Original
2016-05-25 17:13:071211browse

[PHP]代码 

$array = array(1,2,3,4,11,12,124,1245);
function found($array,$low,$hight,$k)
{
	$index = intval(($low+$hight) / 2);
	if($k == $array[$index])
	{
		return $index;
	}elseif($k < $array[$index])
	{
		return found($array,$low,$index-1,$k);
	}else{
		return found($array,$index+1,$hight,$k);
	}

}
echo found($array,0,$count,1245);

/**改进型不使用递归*/
function find($arr,$v)
{
	$start = 0;
	$end   = count($arr) - 1;

	while($start <= $end)
	{
		$index = intval(($start + $end) / 2);
		
		if($v < $arr[$index])
		{
			$end = $index - 1;
		}
		elseif($v > $arr[$index])
		{
			$start = $index + 1;
		}
		else
		{
			return $index;
		}
	}
	return -1;
}

                   

                   

Statement:
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