The selection problem asks for one ranked element, whereas sorting asks for the complete order. This distinction lets quickselect discard work that cannot affect the requested rank. Counting sort and LSD radix sort go further: they can cross the comparison-sorting barrier by using structure in the keys, but only under explicit range and digit assumptions.
Motivation
Suppose a list contains millions of values and we need only its median. Sorting will answer the question, but the complete sorted order contains much more information than one median. A useful algorithmic habit is therefore to ask what output the problem actually requires before choosing a familiar routine.
Full sorting establishes every rank. Partial selection sort stops after placing the first few order statistics. Quickselect discards more work: after a partition it continues only on the side that can contain the requested rank. Counting and radix methods make a different change. They exploit a bounded integer range or a fixed digit representation, so their costs must include those parameters as well as the number of keys.
These selection algorithms answer a static, one-query problem. Sorting once may be reasonable for many rank queries on unchanged data. With intervening insertions and deletions, a search tree augmented with subtree sizes can support rank queries, but a logarithmic guarantee also requires maintained balance. The ordinary BST operations provide neither balance nor subtree-size maintenance automatically. Static selection and dynamic order statistics therefore have different invariants and cost obligations.
Definitions
Definition 3.2.1
(Selection problem)
Given a list of keys and an integer satisfying , return the kth smallest key. Rank is one-based, while array indices in pseudocode may be zero-based. Duplicate keys are counted with multiplicity: in , the first and second smallest keys are both .
The cases and are the minimum and maximum. Each needs a single scan, so selection cannot have a general lower bound of in the comparison model. The lower bound later in this note is about producing a complete sorted order, not about finding one rank.
Partial selection sort performs the first rounds of selection sort. In
round , it finds the minimum of the remaining suffix and swaps it into
position . It then returns A[k - 1]; it need not physically remove an
array element. Its exact number of key comparisons is
which is . It is linear when is a fixed constant, but quadratic when is proportional to .
Definition 3.2.2
(Partition contract)
For a current subarray of length , Partition returns an index , places
the chosen pivot at A[p], and guarantees that every index below contains
a key at most A[p], while every index above contains a key at least
A[p]. Thus the pivot value is a valid key of local rank , even when
equal keys occur. This final-pivot-index contract is stronger than a routine
that returns only a boundary between two regions.
With one-based rank relative to the current subarray, correct quickselect branching is:
Quickselect(A, m, k):
require 1 ≤ k ≤ m
if m == 1: return A[0]
p = Partition(A, m) // p is the pivot's final 0-based index
if k - 1 == p: return A[p]
if k - 1 is below p: return Quickselect(A[0:p], p, k)
return Quickselect(A[p+1:m], m-p-1, k-p-1)
The equality branch is essential. On the right, the new rank subtracts the left-side positions and the pivot itself.
At the start of every recursive call, the invariant is: the current subarray contains the original requested order statistic, and its parameter is that value's rank within this subarray. The left call preserves because no smaller positions have been discarded. The right call discards exactly positions, so it uses . The base case is reachable because an equality return stops at the pivot and either recursive branch is strictly shorter than its parent. A routine returning a Hoare-style boundary rather than the pivot's final index needs a different argument and must not be dropped into this pseudocode unchanged.
Randomized three-way quickselect
The pseudocode above uses a two-way final-index partition. For the expected-time guarantee on inputs that may contain duplicates, use a separate three-way variant. Choose one current record uniformly at random as the pivot, then partition into strict-less block , equal block , and strict-greater block . With one-based local rank and , :
RandomizedQuickselect(A, m, k):
pivot = key of a uniformly random record in A
(L, E, G) = ThreeWayPartition(A, pivot)
if k ≤ |L|: return RandomizedQuickselect(L, |L|, k)
if k ≤ |L| + |E|: return pivot
return RandomizedQuickselect(G, |G|, k-|L|-|E|)
The same recursive-call invariant holds, but the discarded prefix on the greater branch now has size . Every recursive call uses a strict block, so it is shorter; if all keys are equal, is the whole input and the algorithm returns after one partition. This three-way contract is also different from a Hoare boundary and must be implemented and proved on its own terms.
Definition 3.2.3
(Stable sorting)
A sorting routine is stable if records with equal keys keep their relative input order in the output. Stability matters when a later pass sorts on one part of a compound key and must preserve order established by earlier passes.
Stable merge sort: a comparison-based example
Stability is easiest to inspect when a record carries information beyond its
sorting key. Write 2A for a record with key 2 and identity A: only the
number participates in comparisons. Sorting [2A,1B,2C,1D] should place the
key-1 records first. A stable result is [1B,1D,2A,2C], because B preceded
D and A preceded C in the input. Alphabetical label order is not the
rule; labels merely let us see whether identities crossed.
Merge sort gives a comparison-based way to obtain this property. Split a contiguous segment into two halves, recursively sort each half, then merge the two sorted sequences. Empty and singleton segments need no comparisons. A merge maintains a cursor into each half and an initially empty output:
while both halves have remaining records:
if left.key ≤ right.key: append the left record; advance left
otherwise: append the right record; advance right
append the remaining suffix of the nonempty half
The equality in ≤ is the important choice. The halves are consecutive
pieces of the original sequence, so every left-half record originally came
before every right-half record. Choosing the left head when keys tie preserves
that cross-half order. Taking the right head on equality would still sort the
keys, but merging [2A] with [2C] would produce [2C,2A] and lose stability.
Proof X-ray
The merge invariant and the stability step
Before each append, the output is sorted, it contains exactly the records already removed from the two halves, and no output key exceeds either remaining head. Each remaining half is still sorted. Therefore its head is its smallest remaining key, and taking the smaller head preserves the invariant; when one side is empty, its partner's suffix can be appended in order. Every append removes one record, so the merge terminates with exactly the original records in sorted order.
Prove stability by induction on segment length. It is immediate for lengths zero and one. The recursive calls preserve the relative order of equal-key records that lie in the same half. For equal-key records in opposite halves, the left one is earlier in the original input, and the left-on-equality rule outputs it first. These two cases cover every pair of equal-key records. Sortedness alone would not prove this second conclusion.
For the four-record example, the recursive results are [1B,2A] and
[1D,2C]. The last merge takes 1B on the first tie, then 1D, then
2A on the second tie, then the remaining 2C. In an odd-length segment,
splitting at floor(n/2) gives halves whose lengths differ by one; neither
the invariant nor the stability proof requires equal lengths.
For a conventional implementation that reuses one auxiliary array, merging records takes time. The recurrence is , giving for : each recursion level processes at most records, and the balanced splitting has levels. The auxiliary array uses space and the recursion stack uses ; this version is not in-place. These bounds describe the sorting algorithm, not a recording of every intermediate array. This teaching explorer retains copied snapshots after each append; its stored trace can use record references. It is deliberately restricted to small examples and should not be used to measure the algorithm's space usage.
Quick check
(Merge [1A,3B] with [1C,2D]. What is the stable result, and which decision protects stability?)
The result is [1A,1C,2D,3B]. Taking 1A rather than 1C at the initial
tie preserves the input order of the key-1 records. Subsequent decisions
compare 3B with 1C, then 3B with 2D, and finally append 3B.
This example sorts arbitrary comparable keys without a bounded integer key range. It therefore remains within the comparison-sorting model. Counting sort below obtains a different bound by using additional information about which integer keys are possible.
Definition 3.2.4
(Counting sort)
For integer keys in the inclusive range , standard stable counting sort uses counters. It counts frequencies, converts them to prefix counts, and scans the input from right to left while placing records in a separate output array. Its time is and its auxiliary space is when both the output and count arrays are included. This standard stable version is not in-place.
After accumulation, C[x] is the number of records with key at most .
During right-to-left placement, --C[x] selects the last unused position in
key 's output block. The counters must be initialized to zero, and maximum
key means valid counters C[0] through C[K]: exactly cells.
Definition 3.2.5
(LSD radix sort)
Let every nonnegative key have digits in base . Least-significant-digit (LSD) radix sort stably sorts the whole array by digit , then digit , and continues through digit . If each pass is stable counting sort on digit values, the total time is and the auxiliary space is .
For -bit machine words grouped into -bit digits, and , so the cost is . Larger digits reduce passes but enlarge the counter array; smaller digits use compact counters but scan the array more times.
The word “linear” is therefore conditional. Counting sort is when . LSD radix sort is when the chosen representation makes constant and , for example fixed-width machine words with a suitable digit size. Negative keys, variable-length representations, or a huge key universe require additional handling rather than an unqualified linear-time claim.
Counting and LSD radix sort copy whole records while using a bounded integer or extracted digit for direct addressing. Stability is therefore about record identity, not visually indistinguishable equal numeric values.
Theorem/Proposition
Theorem 3.2.6
(Why quickselect can avoid full sorting)
Assume Partition satisfies the final-pivot-index contract. If its returned
index is , a target of local rank equals the pivot; a smaller target
rank lies in the left subarray; and a larger target rank lies in the right
subarray with adjusted rank . Consequently quickselect needs at most one
recursive call after each partition.
Theorem 3.2.7
(Decision-tree lower bound for comparison sorting)
For arbitrary inputs of distinct keys, every deterministic comparison-based sorting algorithm has a worst-case execution using comparisons. This statement assumes that key comparisons are the only way to learn their relative order; it does not apply unchanged when bounded integers can be used as array indices.
Theorem 3.2.8
(Correctness of LSD radix sort)
After completing stable passes on digits , the array is sorted by the -digit suffix viewed as a base- number. Hence, after all passes, the array is sorted by the complete key.
Proof sketch or proof idea
Quickselect branch correctness and cost
After partitioning, the pivot is in a position it could occupy in a completely sorted current subarray. Every position to its left contains a key no larger, and every position to its right contains a key no smaller. Therefore a target index below cannot require the right side, and a target index above cannot require the left side. Equality returns immediately. This proves the one-branch theorem; no assumption that either side is already internally sorted is needed.
Partitioning costs on a subproblem of size . If every pivot is extreme, the sizes are , giving . A perfectly balanced shrink gives the useful intuition , but that geometric series alone is not an average-case proof.
For the randomized three-way variant, assume each call chooses a record uniformly and independently from the current subarray and that comparisons and swaps take constant time. Give equal occurrences arbitrary consecutive ranks in sorted order. With probability at least , the chosen record's rank is in the middle half. Its strict-less and strict-greater blocks then both have size at most ; the target either returns from the equal block or survives in one of those strict blocks. The expected number of trials before such a shrink is at most two, and all partitions at that size scale cost in expectation. Summing over geometrically shrinking scales gives expected . The first partition costs in this model, so the expected time is . All-equal input takes one linear pass, while distinct-key extreme pivots still give a worst case.
Decision-tree lower-bound proof
For distinct arbitrary keys, all relative orders are possible. A deterministic comparison sort can be represented by a binary decision tree: each internal node compares two keys, and each leaf identifies the input permutation. Correctness requires at least leaves. A binary tree of height has at most leaves, so and . Let . The largest factors in are each at least , so
Thus some input follows a path of that length. Counting and radix sort do not contradict the result: they use digit extraction, arithmetic, and direct array addressing, and they restrict the key representation.
Concept lensAlgorithmic
The same bound as an adversary strategy
Read the bound as a game. An adversary keeps the set of key orders consistent with every answer so far, starting with all . Each comparison splits that set in two, and the adversary answers so as to keep the larger part. After comparisons at least orders remain, and the algorithm cannot stop while two remain, so again .
LSD radix invariant
The invariant describes the order of a suffix, not the order of the whole key after every pass. Number the digits from the right, starting at , and write for digit of key in base . Define
Thus is the last digit, is the number formed by the last two digits, and so on. Leading zeroes allow all keys to use the same fixed number of digits. After pass , the claim is that the array is in nondecreasing order of ; higher, unprocessed digits may still be out of order.
The first pass sorts by , which establishes the base case. For the inductive step, take and suppose the input to pass is already sorted by . This pass groups the records in increasing order of . Within a group whose current digit is , stability retains the input order, so the lower suffix is still nondecreasing there. Since
every suffix in digit group is smaller than every suffix in digit group whenever . The groups are therefore correctly ordered, and each group is correctly ordered internally. This proves the invariant for pass . After pass , , so the invariant is the required full numeric order.
Proof X-ray
The information that a stable pass must preserve
The new digit is the primary ordering criterion; the lower-digit suffix, ordered by earlier passes, is the secondary criterion. A digit sort alone establishes only the primary order. Stability supplies the secondary order without comparing or sorting the suffix again.
In this argument, “equal keys” for the digit subroutine means equal extracted digits, not equal complete numbers. For example, and are different numbers but tie when the tens digit is the current sorting key. A stable tens pass must preserve their previously established units order.
For numeric correctness, the first, units-only pass does not itself need to be stable: there is no earlier suffix order to preserve. To maintain the invariant, later passes must preserve the lower-suffix order inside each current-digit group; a stable subroutine guarantees this for every input. Using that same stable routine on all passes is the standard uniform implementation. If the final output must also preserve the original record order for duplicate complete keys, an unstable first pass can lose that additional guarantee.
Worked examples
Worked example 3.2.9
(Partial selection cost)
For the array
, finding the fourth smallest key by
partial selection places , then , then , then into the first four
positions. With and , the four suffix scans make
comparisons, and A[3] is .
This is substantially less than all comparisons of a full selection sort on thirteen elements, but the advantage depends on small . For a median-scale rank, and the method becomes quadratic.
Worked example 3.2.10
(Quickselect partition trace)
Find the second smallest key in , always taking the first element of the current subarray as pivot.
- Partition around to obtain . The pivot has index , or rank , so rank lies in the left subarray .
- Partition that subarray around . The pivot has local rank , so move right and adjust the target to .
- In , pivot has local rank . The equality branch returns .
The untouched partitions need not be sorted. The trace also shows why omitting the equality return or forgetting the right-side rank adjustment is a real correctness error.
For the list and rank , choose the first value as pivot. The less, equal and greater blocks are , and . Since , the answer is ; no further partition is needed.
Worked example 3.2.11
(Counting sort from counts to stable placement)
Let and . The six counters for keys through are
After prefix accumulation,
where counts keys at most . Scanning from right to left, place a
record of key at index --C'[x]. For example, the final input key sees
count , decrements it to , and occupies output index . Repeating this
operation produces
Right-to-left scanning matters when equal keys carry distinct records: the later equal record takes the later available output position, so their input order is preserved. The three phases cost , , and , hence overall.
Worked example 3.2.12
(Why stability matters in radix sort)
Apply base- LSD radix sort to :
- stable ones-digit pass: ;
- stable tens-digit pass: ;
- stable hundreds-digit pass: .
In the tens pass, for instance, remains before among keys with tens digit because their ones digits were already ordered. An unstable pass could reverse that pair and destroy the lower-digit ordering on which the induction proof depends.
Counterexample mode
Sorting each digit is not enough
False claim: LSD radix sort is correct whenever each pass sorts its current digit, even if ties may be reordered arbitrarily.
Consider the two-digit input in base . A stable units pass produces
The units digits are now . The order before is allowed at this stage: only the units suffix has been sorted, not the whole number. Next sort by the tens digit, but reverse the records within each equal-tens group. The tens- group becomes , and the tens- group becomes . This gives
The second pass has correctly sorted its own digit: the tens digits are . Nevertheless, the final array is not numerically sorted, since and . The pass destroyed the units order within both tens groups, and there are no remaining passes to repair it. No duplicate complete keys are involved; ties in the current digit are sufficient for failure.
With a stable tens pass, the groups instead retain the orders and , giving . To maintain the invariant, each later pass can retain the already sorted lower suffix among records tied on the current digit. Stability guarantees that condition. This counterexample shows that removing stability loses a general correctness guarantee; it does not claim that every run of an unstable digit routine must fail. For example, on , an unstable tens pass could reverse the two records to after the units pass; a hundreds pass then restores . This run temporarily breaks the suffix invariant but ends sorted.
Common mistakes
- Accepting or , or mixing one-based ranks with zero-based indices.
- Treating a partition boundary as though it were necessarily the pivot's final index.
- Omitting quickselect's equality return or failing to subtract when recursing right.
- Claiming quickselect is always linear, presenting balanced shrink as an average-case proof without a uniform randomized-pivot model, or omitting the three-way equal block when duplicates are allowed.
- Writing that sorting takes “at least ”; use for the comparison lower bound and state its assumptions.
- Allocating only counters for the inclusive key range , or forgetting to initialize all counters to zero.
- Calling the standard stable counting sort in-place, or scanning left to right while using decreasing prefix-count positions.
- Saying every radix-sort organization needs the same stable-pass argument. The theorem here is specifically for whole-array LSD radix sort.
- Quoting or dynamic-set operations without the required capacity, expected-hashing, or height-balance assumptions.
Summary
- Selection returns one order statistic; sorting returns all rank information.
- Partial selection costs and is attractive only when is small.
- A two-way final-index partition lets quickselect recurse on one side. The duplicate-safe uniformly randomized three-way variant returns from its equal block and has expected time. All-equal input is ; worst case is .
- Comparison sorting of arbitrary distinct keys needs comparisons in the worst case by the decision-tree proof.
- Stable counting sort on keys uses counters, runs in , scans right to left for stability, and is not in-place in its standard output-array form.
- LSD radix sort with base- digits and stable digit passes runs in . Its linearity depends on the representation parameters.
Exercises
Quick check
(Why is full sorting more work than selection?)
Compare the requested output.
Solution · Answer
Selection asks for one ranked element. Sorting asks for the complete order of all elements, which contains more information than a single kth item.
Quick check
(What extra assumption lets counting sort run in linear time?)
Think about the count array.
Solution · Answer
The key range must be bounded so that the count array is not larger than a constant multiple of the input size; commonly this is stated as .
Quick check
(Does a numerically correct LSD radix sort require stability on its very first digit pass?)
Distinguish sorting the numeric keys from preserving the original order of records with duplicate complete keys.
Solution · Answer
For numeric order alone, no: the first pass only has to sort digit , because there is no earlier suffix order to preserve. To maintain the invariant, subsequent passes preserve lower-suffix order within current-digit ties; stability guarantees this condition. However, an unstable first pass can reorder duplicate complete keys, so it can lose the additional guarantee that the final record sort is stable.
- Explain why quickselect recurses on only one partition side, including the equality case.
- Give a case where partial selection sort is reasonable, and a case where it is not.
- Explain what order later LSD radix passes can preserve to maintain the invariant, and how stability guarantees it. Why is the first pass different if only numeric order is required? What additional requirement applies if the final record sort must preserve the original order of duplicate complete keys?
- For and , compute the exact comparison count of partial selection sort under the suffix-scan implementation.
- Starting from prefix counts , state where the rightmost key is placed and what its counter becomes.
- Explain precisely why counting sort and radix sort do not violate the comparison-sorting lower bound.
Solutions
Solution · Guided solutions
- Once the pivot's final index is known, the target rank is either the pivot, strictly left, or strictly right. Equality returns; only the relevant side can contain the remaining target.
- It is reasonable when is a small constant and only a few minimum-selection rounds are needed. It is poor for , such as a median, because its cost becomes quadratic.
- To maintain the invariant, later passes must keep the lower-digit suffixes nondecreasing within each current-digit group. Stability guarantees this by preserving the input order within that group; an arbitrary tie order can destroy it. For numeric correctness, the first pass only has to sort digit , since no earlier suffix order exists. A stable final record sort must additionally preserve the original relative order of records with equal complete keys. Stable passes starting with the first guarantee that property. For example, if an unstable first pass reverses two records both keyed , later stable passes preserve that reversed order: numeric sorting can be correct while the final record sort is not stable.
- The count is comparisons.
- The value is decremented to , so the record is placed at zero-based output index .
- The lower bound assumes arbitrary distinct keys and learns order only through comparisons. Counting and radix sort restrict key representations and also use arithmetic, digit extraction, and direct addressing.