Chapter 1

Searching and comparison sorting

First identify the data order and the exact operation being counted. A key comparison, an array write and a swap are different costs. In this chapter nn is the number of array elements; OO means an asymptotic upper bound and Θ\Theta a tight bound.

Past papers · CS 2014–2026 (23 papers): 2 questions, 3 marks

Scan until the target is found or the array ends. No ordering is required. Checking whether an array is nondecreasing takes one pass over neighbouring pairs; checking both possible orders maintains two flags during the same pass.

A universal condition on all ordered pairs can sometimes reduce to adjacent comparisons. For example, all successive differences increasing is tested by comparing neighbouring differences in Θ(n)\Theta(n) time, rather than checking every pair.

Past papers · CS 2014–2026 (23 papers): 4 questions, 7 marks · DA 2024–2026 (3 papers): 3 questions, 4 marks

Binary search needs sorted keys and constant-time access to a middle entry. A linked list does not provide logarithmic elapsed time just because the search makes logarithmically many key comparisons. Let AA be an ascending array of length nn and xx the target.

A lower bound is the first index with A[i]≥xA[i]\ge x; an upper bound is the first index with A[i]>xA[i]>x. Either may equal nn. Their difference counts occurrences of xx. This half-open implementation finds the lower bound:

def lower_bound(A, x):
    lo, hi = 0, len(A)
    while lo < hi:
        mid = lo + (hi - lo) // 2
        if A[mid] < x:
            lo = mid + 1
        else:
            hi = mid
    return lo

The invariant is: entries before lo are smaller than xx, and entries at or after hi are at least xx. The unresolved interval shrinks each time. The same method locates the first true value of a monotone Boolean predicate.

1.3 Elementary sorts and inversions

Past papers · CS 2014–2026 (23 papers): 5 questions, 6 marks · DA 2024–2026 (3 papers): 4 questions, 7 marks

Selection sort selects the minimum of the remaining suffix and swaps it into the next prefix position. Insertion sort inserts the next entry into a sorted prefix. A left-to-right bubble pass swaps adjacent inversions and places the largest remaining entry at the right end.

Algorithm, conventional array versionBest timeAverage time, uniform distinct permutationsWorst timeStable?Extra space
Selection by swapping minimumΘ(n2)\Theta(n^2)Θ(n2)\Theta(n^2)Θ(n2)\Theta(n^2)NoΘ(1)\Theta(1)
Insertion, shift strictly larger keysΘ(n)\Theta(n)Θ(n2)\Theta(n^2)Θ(n2)\Theta(n^2)YesΘ(1)\Theta(1)
Bubble, stop after a no-swap passΘ(n)\Theta(n)Θ(n2)\Theta(n^2)Θ(n2)\Theta(n^2)YesΘ(1)\Theta(1)

A stable sort preserves the input order of equal keys. Unconditional bubble passes make n(n−1)/2n(n-1)/2 comparisons even on sorted input. Binary insertion reduces search comparisons but still has quadratic worst-case shifts. For a random distinct permutation, each pair is inverted with probability 1/21/2, so E[I]=n(n−1)/4E[I]=n(n-1)/4.

1.4 Merging and mergesort

Past papers · CS 2014–2026 (23 papers): 1 question, 1 mark

Divide into two nearly equal parts, sort each and merge their sorted outputs. During merging, compare the two front entries and copy the smaller; when one list empties, copy the other without further key comparisons. Choose the left item on equality to preserve stability.

Ordinary mergesort performs n−1n-1 merges of nonempty runs. A merge output is simply left-run followed by right-run exactly when the largest left key is at most the smallest right key. An implementation can test this boundary and skip merging; the ordinary implementation still copies entries. Thus linear best time belongs to an explicitly adaptive variant, not to the standard recurrence.

During an inversion-counting merge, if the next right key is strictly smaller than the next left key, add the number of unmerged left keys. Equal keys add zero. Total time is Θ(nlog⁡n)\Theta(n\log n).

1.5 Quicksort and partitioning

Past papers · CS 2014–2026 (23 papers): 4 questions, 4 marks · DA 2024–2026 (3 papers): 2 questions, 2 marks

Partition around a pivot, then sort the parts. In the recurrence below the pivot is placed in its final position and excluded from both recursive calls. A partition boundary returned by another scheme need not be a pivot position: read the contract before setting endpoints.

Pivot/split conditionTimeOrdinary recursive stack
Both parts remain a fixed positive fraction of the inputΘ(nlog⁡n)\Theta(n\log n)Θ(log⁡n)\Theta(\log n)
Always an extreme keyΘ(n2)\Theta(n^2); n(n−1)/2n(n-1)/2 comparisons in the stated modelΘ(n)\Theta(n)
Uniform random rankExpected Θ(nlog⁡n)\Theta(n\log n); worst Θ(n2)\Theta(n^2)Expected O(log⁡n)O(\log n); worst Θ(n)\Theta(n)

The probability of an extreme first pivot is 2/n2/n for n≥2n\ge2 distinct keys. Always selecting the middle position does not guarantee balanced ranks. Sorted input is quadratic for first/last-pivot conventional quicksort, not for every pivot rule. Standard in-array partitioning uses constant local storage and is not stable. Recursing only on the smaller part and looping over the larger part caps the stack at O(log⁡n)O(\log n) even when time is quadratic. Three-way partitioning groups equal keys and avoids repeatedly sorting them.

Last-minute recall

  • Linear search does not need sorted input; binary search does.
  • One probe need not mean one Boolean comparison in code.
  • Insertion and bubble adjacent swaps count strict inversions.
  • Selection sort comparison count is independent of input order.
  • A stable merge takes the left key on equality.
  • Partition endpoints depend on the partition contract.
  • Randomized quicksort has quadratic worst time.
  • Include recursion storage when asked for auxiliary space.

Revise offline: the whole Algorithms handbook as one PDF

52 pages · 2.6 MBFree to read online. Sign in to download the PDF.We save the handbook, version and request time in My downloads. Privacy policy

All chapters · Corrections