Primary algorithm: Two-point lookup

Source: Internet
Author: User

If you have a list that lets you find 66 of the locations from this list, what do you want to do?

L = [2,3,5,10,15,16,18,22,26,30,32,35,41,42,43,55,56,66,67,69,72,76,82,83,88]

You say so easy!

L.index (66) ...

We can find this using the index method, because Python helps us find the way. If, the index method does not give you the use of ... Can you still find this 66?

View Code

The above method realizes the location of 66 from a list.

But how do we find this number now? is not the cycle of this list, one to find AH? If we have a very long list, and we have a good hundreds of thousands of-digit number, do we need to compare a hundred thousand of times if we have bad luck? It's so inefficient, we have to think of a new way.

binary search Algorithm
L = [2,3,5,10,15,16,18,22,26,30,32,35,41,42,43,55,56,66,67,69,72,76,82,83,88]

Do you observe this list, which is not an ordered list of small to large sort?

If that's the case, if I'm looking for a larger number than the middle of the list, am I just going to look in the back half of the list?

This is the binary search algorithm !

So how do we implement it in the code?

Simple version of Binary method

View Code

Two-way version of the upgrade

View Code

Primary algorithm: Two-point lookup

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.