World Library  
Flag as Inappropriate
Email this Article

Comparison sort

Article Id: WHEBN0003189304
Reproduction Date:

Title: Comparison sort  
Author: World Heritage Encyclopedia
Language: English
Subject: Sorting algorithm, Quicksort, Radix sort, Adaptive sort, Sorting network
Publisher: World Heritage Encyclopedia

Comparison sort

Sorting a set of unlabelled weights by weight using only a balance scale requires a comparison sort algorithm

A comparison sort is a type of sorting algorithm that only reads the list elements through a single abstract comparison operation (often a "less than or equal to" operator or a three-way comparison) that determines which of two elements should occur first in the final sorted list. The only requirement is that the operator obey two of the properties of a total order:

  1. if ab and bc then ac (transitivity)
  2. for all a and b, either ab or ba (totalness or trichotomy).

It is possible that both ab and ba; in this case either may come first in the sorted list. In a stable sort, the input order determines the sorted order in this case.

A metaphor for thinking about comparison sorts is that someone has a set of unlabelled weights and a balance scale. Their goal is to line up the weights in order by their weight without any information except that obtained by placing two weights on the scale and seeing which one is heavier (or if they weigh the same).


  • Examples 1
  • Performance limits and advantages of different sorting techniques 2
  • Alternatives 3
  • Number of comparisons required to sort a list 4
    • Lower bound for the average number of comparisons 4.1
  • Notes 5
  • References 6


Quicksort in action on a list of numbers. The horizontal lines are pivot values.

Some of the most well-known comparison sorts include:

Performance limits and advantages of different sorting techniques

There are fundamental limits on the performance of comparison sorts. A comparison sort must have an average-case lower bound of Ω(n log n) comparison operations,[1] which is known as linearithmic time. This is a consequence of the limited information available through comparisons alone — or, to put it differently, of the vague algebraic structure of totally ordered sets. In this sense, mergesort, heapsort, and introsort are asymptotically optimal in terms of the number of comparisons they must perform, although this metric neglects other operations. Non-comparison sorts (such as the examples discussed below) can achieve O(n) performance by using operations other than comparisons, allowing them to sidestep this lower bound (assuming elements are constant-sized).

Note that comparison sorts may run faster on some lists; many adaptive sorts such as insertion sort run in O(n) time on an already-sorted or nearly-sorted list. The Ω(n log n) lower bound applies only to the case in which the input list can be in any possible order.

Also note that real-world measures of sorting speed may need to take into account the ability of some algorithms to optimally use relatively fast cached computer memory, or the application may benefit from sorting methods where sorted data begins to appear to the user quickly (and then user's speed of reading will be the limiting factor) as opposed to sorting methods where no output is available for display until the whole list is sorted.

Despite these limitations, comparison sorts offer the notable practical advantage that control over the comparison function allows sorting of many different datatypes and fine control over how the list is sorted. For example, reversing the result of the comparison function allows the list to be sorted in reverse; and one can sort a list of tuples in lexicographic order by just creating a comparison function that compares each part in sequence:

function tupleCompare((lefta, leftb, leftc), (righta, rightb, rightc))
    if lefta ≠ righta
        return compare(lefta, righta)
    else if leftb ≠ rightb
        return compare(leftb, rightb)
        return compare(leftc, rightc)

Balanced ternary notation allows comparisons to be made in one step, whose result will be one of "less than", "greater than" or "equal to".

Comparison sorts generally adapt more easily to complex orders such as the order of floating-point numbers. Additionally, once a comparison function is written, any comparison sort can be used without modification; non-comparison sorts typically require specialized versions for each datatype.

This flexibility, together with the efficiency of the above comparison sorting algorithms on modern computers, has led to widespread preference for comparison sorts in most practical work.


Some sorting problems admit a strictly faster solution than the Ω(n log n) bound for comparison sorting; an example is integer sorting, where all keys are integers. When the keys form a small (compared to n) range, counting sort is an example algorithm that runs in linear time. Other integer sorting algorithms, such as radix sort, are not asymptotically faster than comparison sorting, but can be faster in practice.

The problem of sorting pairs of numbers by their sum is not subject to the Ω(n² log n) bound either (the square resulting from the pairing up); the best known algorithm still takes O(n² log n) time, but only O(n²) comparisons.

Number of comparisons required to sort a list

n \lceil\log_2(n!)\rceil Minimum
1 0 0
2 1 1
3 3 3
4 5 5
5 7 7
6 10 10
7 13 13
8 16 16
9 19 19
10 22 22
11 26 26
12 29 30[2]
13 33 34[3]
14 37 38[3]
15 41 42[4]
16 45 45 or 46[5]
19 57 58[4]
22 70 71[3]
n \lceil\log_2(n!)\rceil n \log_2 n - \frac{n} {\ln 2}
10 22 19
100 525 521
1 000 8 530 8 524
10 000 118 459 118 451
100 000 1 516 705 1 516 695
1 000 000 18 488 885 18 488 874
Above: A comparison of the lower bound \lceil\log_2(n!)\rceil to the actual minimum number of comparisons (from  A036604) required to sort a list of n items. Below: Using Stirling's approximation, this lower bound is well-approximated by n \log_2 n - \frac{n} {\ln 2}.

The number of comparisons that a comparison sort algorithm requires increases in proportion to n\log(n), where n is the number of elements to sort. This bound is asymptotically tight.

Given a list of distinct numbers (we can assume this because this is a worst-case analysis), there are n factorial permutations exactly one of which is the list in sorted order. The sort algorithm must gain enough information from the comparisons to identify the correct permutation. If the algorithm always completes after at most f(n) steps, it cannot distinguish more than 2f(n) cases because the keys are distinct and each comparison has only two possible outcomes. Therefore,

2^{f(n)}\geq n!, or equivalently f(n)\geq\log_2(n!).

From Stirling's approximation we know that \log_2(n!) is \Omega(n \log_2 n). This provides the lower-bound part of the claim.

An identical upper bound follows from the existence of the algorithms that attain this bound in the worst case.

The above argument provides an absolute, rather than only asymptotic lower bound on the number of comparisons, namely \lceil\log_2(n!)\rceil comparisons. This lower bound is fairly good (it can be approached within a linear tolerance by a simple merge sort), but it is known to be inexact. For example, \lceil\log_2(13!)\rceil=33, but the minimal number of comparisons to sort 13 elements has been proved to be 34 .[3][6]

Determining the exact number of comparisons needed to sort a given number of entries is a computationally hard problem even for small n, and no simple formula for the solution is known. For some of the few concrete values that have been computed, see  A036604.

Lower bound for the average number of comparisons

A similar bound applies to the average number of comparisons. Assuming that

  • all keys are distinct, i.e. every comparison will give either a>b or a, and
  • the input is a random permutation, chosen uniformly from the set of all possible permutations of n elements,

it is impossible to determine which order the input is in with fewer than log2(n!) comparisons on average.

This can be most easily seen using concepts from information theory. The Shannon entropy of such a random permutation is log2(n!) bits. Since a comparison can give only two results, the maximum amount of information it provides is 1 bit. Therefore after k comparisons the remaining entropy of the permutation, given the results of those comparisons, is at least log2(n!) - k bits on average. To perform the sort, complete information is needed, so the remaining entropy must be 0. It follows that k must be at least log2(n!).

Note that this differs from the worst case argument given above, in that it does not allow rounding up to the nearest integer. For example, for n = 3, the lower bound for the worst case is 3, the lower bound for the average case as shown above is approximately 2.58, while the highest lower bound for the average case is 8/3, approximately 2.67.

In the case that multiple items may have the same key, there is no obvious statistical interpretation for the term "average case", so an argument like the above cannot be applied without making specific assumptions about the distribution of keys.


  1. ^  
  2. ^ M. Wells, Elements of Combinatorial Computing, Pergamon Press, Oxford, 1971.
  3. ^ a b c d Marcin Peczarski, New Results in Minimum-Comparison Sorting. Algorithmica 40(2):133-145, 2004.
  4. ^ a b Cheng Weiyi, Liu Xiaoguang, Wang Gang et al. The results of S(15) and S(19) to minimum-comparison sorting problem. Journal of Frontiers of Computer Science and Technology, 2007, 1(3): 305-313.
  5. ^ Peczarski, Marcin (3 August 2011). "Towards Optimal Sorting of 16 Elements". 
  6. ^ Marcin Peczarski: The Ford-Johnson algorithm is still unbeaten for less than 47 elements. Inf. Process. Lett. 101(3): 126-128 (2007) doi:10.1016/j.ipl.2006.09.001


This article was sourced from Creative Commons Attribution-ShareAlike License; additional terms may apply. World Heritage Encyclopedia content is assembled from numerous content providers, Open Access Publishing, and in compliance with The Fair Access to Science and Technology Research Act (FASTR), Wikimedia Foundation, Inc., Public Library of Science, The Encyclopedia of Life, Open Book Publishers (OBP), PubMed, U.S. National Library of Medicine, National Center for Biotechnology Information, U.S. National Library of Medicine, National Institutes of Health (NIH), U.S. Department of Health & Human Services, and, which sources content from all federal, state, local, tribal, and territorial government publication portals (.gov, .mil, .edu). Funding for and content contributors is made possible from the U.S. Congress, E-Government Act of 2002.
Crowd sourced content that is contributed to World Heritage Encyclopedia is peer reviewed and edited by our editorial staff to ensure quality scholarly research articles.
By using this site, you agree to the Terms of Use and Privacy Policy. World Heritage Encyclopedia™ is a registered trademark of the World Public Library Association, a non-profit organization.

Copyright © World Library Foundation. All rights reserved. eBooks from Project Gutenberg are sponsored by the World Library Foundation,
a 501c(4) Member's Support Non-Profit Organization, and is NOT affiliated with any governmental agency or department.