Simple but practical binary method (1)

Source: Internet
Author: User

As a beginner of C, the binary method basically needs to be learned. Let's briefly describe the idea of binary, for example, giving you 10 numbers: 1, 3, 5, 4, 6, 10, 9, 8, 7, 2. the easiest way to search for a number, such as 2, is to traverse from the first number to the last number.

for(i = 0; i < n; i++){      if(a[i] == m)       break;}.........

But there is a problem. If the value of N is very large, it is as large as 1000000, and 10000000, it will obviously fail and will time out. What should we do? This is our turn to the appearance of the binary method.

The binary method, as its name implies, divides all data into two halves each time. Of course, an important prerequisite for the use of the binary method is that the series must be ordered. That is to say, if the sequence given to you by the question is unordered, you must first sort it to use binary (the sort function is recommended for sorting, which can be Baidu to), or the 10 numbers, after sorting is: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10. Take the median value (MID) every time. For example, you can still find 2. For the first time, mid = (1 + 10)/2 = 5, 2 <5, so the interval is 1 ~ 5, and then take mid = (1 + 5)/2 = 3> 2, and then take the range 1 ~ 3. Then, execute the preceding operation to obtain the number of queries 2 ,. In this way, 2 is found three times, and the first is 10 times. For the second part, because each time is half of the number, so the number of 1000000 is as long as n = log2000000, it is about 20 times. This is much faster than the general search method.

While (L <r) // L is the left boundary, and r is the right boundary {mid = (L + r)/2; // take the intermediate value if (mid> X) // update the boundary and draw a picture. X is the value {r = mid;} If (mid <X) {L = mid;} If (mid = X) {printf ("this number is found") ;}} printf ("this number is not found ");

 

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.