PHP Two-point lookup algorithm detailed

Source: Internet
Author: User
Tags key

First, the concept: Two-point search also known as binary search, the advantage is that less than the number of times, the search speed, the average performance is good; its disadvantage is to request the table is ordered table, and insert delete difficult. Therefore, the binary lookup method is suitable for frequently ordered lists that are infrequently changed. First, suppose that the elements in the table are sorted in ascending order, compares the keywords in the middle position record of the table to the lookup key, and if the two are equal, the search succeeds; otherwise, the table is divided into the preceding and the last two child tables using the middle position record, and the previous child table is further searched if the key of the middle position record is greater than the lookup keyword Otherwise, the next child table is further searched. Repeat the process until you find a record that satisfies the criteria, make the lookup successful, or until the child table does not exist, the lookup is unsuccessful.

Second, code: for unordered arrays, use the following methods.

Header ("content-type:text/html;charset= ' Utf-8 '");
function Twosearchmethod ($arr, $val, $left, $right) {
	if ($left > $right) {
		echo "cannot find this value";
		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 "
"; $val =1; Twosearchmethod ($arr, $val, 0, 6);



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.