Home > Backend Development > PHP Tutorial > Detailed explanation of PHP binary search algorithm_PHP tutorial

Detailed explanation of PHP binary search algorithm_PHP tutorial

WBOY
Release: 2016-07-13 10:21:23
Original
920 people have browsed it

Detailed explanation of PHP binary search algorithm

1. Concept: Binary search, also known as half search, has the advantages of less number of comparisons, fast search speed, and good average performance; its disadvantage is that the table to be looked up is required to be an ordered table, and insertion and deletion are difficult. Therefore, the binary search method is suitable for ordered lists that do not change frequently but are searched frequently. First, assuming that the elements in the table are arranged in ascending order, compare the keyword recorded in the middle position of the table with the search keyword. If the two are equal, the search is successful; otherwise, use the middle position record to divide the table into two sub-tables, the first and last. If If the keyword recorded in the middle position is greater than the search keyword, then the previous subtable will be searched further, otherwise the next subtable will be searched further. Repeat the above process until a record that meets the conditions is found, making the search successful, or until the subtable does not exist, in which case the search fails.

2. Code: For unordered arrays, use the following method.

header("Content-type:text/html;charset='utf-8'");
function twosearchmethod($arr,$val,$left,$right){
	if($left>$right){
		echo "找不到该数值";
		return ;
	}
	$middle=round(($left+$right)/2);
	if($arr[$middle]>$val){
		twosearchmethod($arr, $val, $left, $middle-1);
	}elseif($arr[$middle]<$val){
		twosearchmethod($arr, $val, $middle+1, $right);
	}else{
		echo $middle;
	}
	
}
$arr=array(1,9,3,4,5,6,7);
sort($arr);
print_r($arr);
echo "<br/>";
$val=1;
twosearchmethod($arr, $val, 0, 6);
Copy after login

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/859802.htmlTechArticlephp Detailed explanation of binary search algorithm 1. Concept: Binary search is also called half search. The advantage is that the number of comparisons is less, and the search It is fast and has good average performance; its disadvantage is that the table to be looked up is required to be an ordered table...
Related labels:
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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template