PHP ordered table search-interpolation search

Source: Internet
Author: User
We introduced binary search before, but let's take a look at it. why is it worth a half discount? Instead of 1/4 off or more? Preface:

We introduced binary search before, but let's take a look at it. why is it worth a half discount? Instead of 1/4 off or more?

For example, if you look for "apple" in an English dictionary, do you subconsciously turn the dictionary into the front or back pages? How do you check "zoo" again? Obviously, you will not start to look up from the middle of the dictionary, but will go forward or backward to a certain extent.

Similarly, for example, the value range is 0 ~ Search for 5 in an array with 10000 elements evenly distributed from small to large. we naturally start looking for a smaller array subscript.

The above analysis is actually the idea of interpolation search, which is an improvement of binary search.

Basic idea:

The key of the keyword to be searched is compared with the keyword of the maximum and minimum record in the search table. its core lies in the interpolation calculation formula:
$ Key-$ arr [$ low]
-----------
$ Arr [$ high]-$ arr [$ low]

Code:

 $ Arr [$ middle]) {$ lower = $ middle + 1;} else {return $ middle ;}} return-1 ;}$ arr = array (, 24,, 99); $ pos = insertsearch ($ arr, 62); print ($ pos); echo"
"; Echo $ I;

Summary:

From the time complexity point of view, it is also O (logn), but for a long ordered table, and the keyword distribution for a more even search table, the average performance of interpolation search algorithms is much better than that of binary search algorithms. Otherwise, if the distribution in the array is similar to {2001 ,... For extremely uneven data such as 999998,999999}, interpolation may not be a proper choice.

The above is the content of the PHP ordered table search ---- interpolation search. For more information, see The PHP Chinese website (www.php1.cn )!

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.