Programmer programming art Chapter 2: Jon Bentley: 25th incorrect Binary Search

Source: Internet
Author: User
ArticleDirectory
    • Chapter 2: Binary Search implementation (Jon Bentley: 25th programmers cannot implement it correctly)
    • Introduction
    • Binary Search code
    • Test
    • Summary
Chapter 2: Binary Search implementation (Jon Bentley: 25th ProgramPersonnel cannot implement it correctly)

Author: July
Source: Structure MethodAlgorithmPath

Introduction

Jon Bentley: over 90% of programmers cannot write binary searches correctly.Code. Many people may have heard of this sentence, but I still want to reference the following paragraphs in programming Pearl River:

"Binary Search can solve (Searching pre-sorted Arrays) Problem: as long as the array contains t (that is, the value to be searched), it can be found by constantly narrowing the range containing T. At the beginning, the range covers the entire array. Compare the intermediate items of the array with t to exclude half of the elements and narrow the range by half. In this way, the comparison is repeated and the range is reduced, and T is found in the array, or the original range of T is determined to be null. For tables with n elements, the entire search process must be compared by log (2) n times.
Most Programmers think that writing code is not difficult as long as they understand the above description. But this is not the case. If you do not agree with this, the best way is to put down the books and write them by yourself. Try it.
I had this question at Bell Labs and IBM. Those professional programmers have several hours to write the above description in the language they choose. You can also write Advanced pseudocode. After the examination, almost all programmers thought they had written the correct program. So it took us half an hour to see the results of their code being verified by test cases. After several lectures, the results of more than one hundred people are almost the same: 90% of programmers write programs with bugs (I don't think the code without Bugs is correct ).
I'm surprised: in enough time, only about 10% of professional programmers can write this applet right. However, not to mention this mini-app: Gartner pointed out in the "History and references" section in section 6.2.1 "sorting and searching in art 3rd of computer programming, although some people published the binary search method as early as 1946, it was not until 1962 that someone wrote a bug-free binary search program."-- Jon Bentley, pp. 35-36, programming Pearl (version 1st.

Can you write binary search code correctly? Try again.

Binary Search code

you do not need to explain the principle of binary lookup. However, we must remind you that binary lookup aims at sorting arrays. OK, read the paper to get a glimpse of it, and be aware of it. I will write a copy first. Below is a binary search implementation I wrote (I was called to perform a binary search on the spot for an interview at a company before, but the result may be the same as you, if you have any questions or errors, please leave it blank:

// Binary Search v0.1 implementation version <br/> // copyright @ 2011 July <br/> // readers are welcome to find the bug at any time, email: zhoulei0907@yahoo.cn. </P> <p> // grasp the following key points: <br/> // right = n-1 => while (left <= right) => right = middle-1; <br/> // right = n => while (left <right) => right = middle; <br/> // The calculation of the middle cannot be written outside the while loop; otherwise, it cannot be updated. </P> <p> int binary_search (INT array [], int N, int value) <br/>{< br/> int left = 0; <br/> int right = n-1; <br/> // If int right = N, modify the following two items to ensure one-to-one matching: <br/> // 1. The condition for the following loop is while (left <right) <br/> // 2. When array [Middle]> value is in the loop, right = mid </P> <p> while (left <= right) // cyclic condition, timely change <br/> {<br/> int middle = left + (right-left)> 1); // prevents overflow and shift is more efficient. At the same time, each cycle needs to be updated. </P> <p> If (array [Middle]> value) <br/> {<br/> right = middle-1; // right value assignment, timely change <br/>}< br/> else if (array [Middle] <value) <br/>{< br/> left = middle + 1; <br/>}< br/> else <br/> return middle; <br/> // some readers may think that the values are equal at the beginning, but after all, there are more situations where the array is not equal <br/> // if each loop determines whether it is equal, time consumed <br/>}< br/> return-1; <br/>}< br/>In a simple test, the running result is as follows (of course, if a test is correct, it does not mean that the program has zero bug, and the test depth is far from enough ):

Test

Maybe you have implemented binary search many times before, but now you may want to test it again. Close all webpages, windows, open notepad, or an editor, or directly comment on this article without referring to the programs I wrote or anyone else above, give yourself ten minutes to N hours to write a binary lookup program immediately. After being correctly written independently at one time, you can leave the code and email address, I will upload you a CHM file in this blog post & thirteen PDF files with tags + directories for classic algorithm research (you can also download it from my resource download site: http://download.csdn.net/user/v_july_v ).

Of course, correct writing does not mean anything. If you cannot write it correctly, it does not mean anything. You just need to perform a simple test on Jon Bentley's remarks. Algorithm exchange group 17th: algorithms_17,192036066(Valid in March ). For the next chapter, see Chapter 26th: code and practices for generating inverted indexes based on a given document. Thank you.

Summary

After this article was published, many of my friends tried it on their own. According to the code left by my friends in this articleWhich of the following is the highest error rate?:

  1. The comments have already been quite clear, but there will still be many friends who make such mistakes:
    1. // Grasp the following key points:
    2. // Right = n-1 => while (left <= right) => right = middle-1;
    3. // Right = n => while (left <right) => right = middle;
    4. // The calculation of middle cannot be written outside the while loop; otherwise, it cannot be updated.
  2. Another common mistake is @ Tudou:
    Middle = (left + right)> 1; in this case, the sum of left and right may overflow when the value of left and right is relatively large.
Continue your efforts.

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.