Home > php教程 > PHP源码 > body text

就是简单描述一下顺序查找和二分查找

PHP中文网
Release: 2016-05-25 16:59:33
Original
1131 people have browsed it


array as $k => $v)
		{
			if($v == $val)
			{
				echo '顺序查找成功!';
				exit(0);
			}
		}
		
		echo '顺序查找失败!';
	}
	
	/**
	 * 二分查找法
	 * @param $val 要查找的值
	 */
	public function bin_search($val)
	{
		sort($this->array);
		
		$min = 0;
		$max = count($this->array);
		
		for ($i = $min; $i < $max; $i++)
		{
			$mid = ceil(($min + $max) / 2);
			
			if($val == $this->array[$mid])
			{
				echo &#39;二分查找成功!&#39;;
				exit(0);
			}
			else if($val < $this->array[$mid])
			{
				$max = $mid;
			}
			else if($val > $this->array[$mid])
			{
				$min = $mid;
			}
		}
		
		echo &#39;二分查找失败!&#39;;
	}
}
Copy after login

                   

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!