A method of 7 comparisons for sorting 5 numbers

Source: Internet
Author: User

This article describes a method for sorting 5 numbers, using only 7 comparisons. Suppose the number to be sorted is a,b,c,d,e.

First, A, B is compared , assuming the result is a<b, and then compare c,d, assuming the result is c<d; and then compare the larger of the two groups (that is, compare b,d), assuming the result is b<d, So there is the following relationship, the relationship between the arrows means "<", that is "less than", so far, has been three times compared .

, the meaning of this figure is: A<b<d,c<d

Now insert e into the appropriate position in {A,b,d}, and when looking for a location using the binary lookup method, only two comparisons are required--compare with B first, and then compare with a or D. When e is inserted into {a,b,d}, there are four results in the following:


In these four cases, a maximum of two comparisons are required to insert C into a sequence composed of [ABCD]. Also use the dichotomy method to find the insertion position. Take the first case: C compares with a first, if it is greater than a, and then compared with B, if it is greater than B, it will not be compared with D , because we have known c<d before.


Reference: Computer programming art, Volume III, page:174

Complete



A method of 7 comparisons for sorting 5 numbers

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.