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 is the number of array elements; means an asymptotic upper bound and a tight bound.
1.1 Linear search
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 time, rather than checking every pair.
1.2 Binary search and boundaries
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 be an ascending array of length and the target.
A lower bound is the first index with ; an upper bound is the first index with . Either may equal . Their difference counts occurrences of . 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 , and entries at or after hi are at least . 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 version | Best time | Average time, uniform distinct permutations | Worst time | Stable? | Extra space |
|---|---|---|---|---|---|
| Selection by swapping minimum | No | ||||
| Insertion, shift strictly larger keys | Yes | ||||
| Bubble, stop after a no-swap pass | Yes |
A stable sort preserves the input order of equal keys. Unconditional bubble passes make 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 , so .
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 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 .
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 condition | Time | Ordinary recursive stack |
|---|---|---|
| Both parts remain a fixed positive fraction of the input | ||
| Always an extreme key | ; comparisons in the stated model | |
| Uniform random rank | Expected ; worst | Expected ; worst |
The probability of an extreme first pivot is for 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 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.