Interview algorithm questions: 16 numbers, up to 20 comparisons, find the second largest number?

Source: Internet
Author: User

The stupidest way to do this is to first select the largest number from 16 numbers and then pick the maximum number from the remaining 15 numbers to get the answer, so you need to 15+14=29 the comparison.

Since this question requires that the second largest number be found within 20 comparisons, we would like to have a simple method.

Assuming that the largest of the 16 numbers is a, the second largest is B.

First compare 16 number 22, the larger wins, and then 22 comparisons in the winner, according to this method, the maximum number A is selected, as shown below

The red route is the path through which the maximum number passes.

Next, analyze where B may exist.

Divide 16 numbers into 8 bits on the left and right parts:

1, if A and B in two different parts (a in the left part, B in the right part, then B is the largest of the right part), so according to the above comparison method, B will be in the root node of the right child node, that is, the Red 1 node in the figure;

2, if a, b in the same part (assuming all in the left part, if the same in the right part, the same analysis method), in the left part of the 8 nodes, according to Method 1 continue to divide the search;

In this way the analysis can be known that A and B will certainly make a comparison (think about why). In the figure, if a follows the red route, the position where B may appear is the Red node 1,2,3,4.

Four red positions are compared 3 times.

So ultimately, you need:

8+4+2+1+3=18

Interview algorithm questions: 16 numbers, up to 20 comparisons, find the second largest number?

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.