Binary search of data structure and algorithm

Source: Internet
Author: User

Question: If you have an array of 100 elements that are already sorted, and then give you a number that lets you decide if there is a number in the array, how do you do it?

The simplest way to do this is to start with the first element of the array, and compare it to the number given, until you compare all the elements of the array, and this lookup method is called Simple lookup, which is a cumbersome approach. But we think that since these 100 numbers are already in order, I will first compare the median with the given number, and if the two match then the problem is solved. If the median is larger than the given number, then the given number may exist with the median left, and we can compare the median of those numbers on the left to the given number, and if the median is smaller than the given number, then the given number may be on the right side of the median, and we'll compare the median of the pile on the right with the given number. By following the steps above, if the last number is not found to be the same number as the given number, then the given number does not exist with the array. This method of finding is called two-point lookup method.

Python code example:

Test:

Specific reference:

The first chapter of the graphical algorithm

—————— the end of this article!

Binary search of data structure and algorithm

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.