Lesson 30 +30 XP

Merge Sort, Radix Sort & Comparison of Sorting Algorithms

Merge Sort, Radix Sort & Comparison of Sorting Algorithms

Merge sort guarantees O(n log n) time on every input and is stable - the two properties quick sort lacks. Its key operation, merging two sorted lists, is also the basis of external sorting. The lesson ends with radix sort (a sort that does not compare keys) and a table comparing every sort in this unit.

1. Merging Two Sorted Lists

Idea: keep one pointer at the front of each sorted list. Repeatedly copy the smaller front element to the output and advance that pointer. When one list runs out, copy the rest of the other.

PSEUDO
Algorithm MERGE(A, LO, MID, HI)
// A[LO..MID] and A[MID+1..HI] are sorted; merge them
I ← LO; J ← MID + 1; K ← 0
while I ≤ MID and J ≤ HI do
    if A[I] ≤ A[J] then             // ≤ keeps the sort stable
        TEMP[K] ← A[I]; I ← I + 1
    else
        TEMP[K] ← A[J]; J ← J + 1
    K ← K + 1
copy any remaining A[I..MID] into TEMP
copy any remaining A[J..HI] into TEMP
copy TEMP[0..K-1] back into A[LO..HI]

Example: merge [3 27 38 43] and [9 10 82]

CompareOutput so far
3 vs 93
27 vs 93 9
27 vs 103 9 10
27 vs 823 9 10 27
38 vs 823 9 10 27 38
43 vs 823 9 10 27 38 43
left list empty3 9 10 27 38 43 82

Merging m and n elements takes at most m + n - 1 comparisons: O(m + n).

2. Merge Sort

Divide and conquer:

  1. Divide the array into two halves.
  2. Conquer: sort each half recursively (an array of one element is already sorted).
  3. Combine: merge the two sorted halves.
Algorithm MERGE_SORT(A, LO, HI)
if LO < HI then
    MID ← (LO + HI) div 2
    MERGE_SORT(A, LO, MID)          // sort left half
    MERGE_SORT(A, MID + 1, HI)      // sort right half
    MERGE(A, LO, MID, HI)           // combine

Trace on 38 27 43 3 9 82 10

DIAGRAM
               [38 27 43 3 9 82 10]          split at mid = 3
              /                    \
       [38 27 43 3]             [9 82 10]
        /        \               /     \
   [38 27]     [43 3]        [9 82]    [10]
    /   \       /   \         /  \
  [38] [27]   [43]  [3]     [9]  [82]

 merge:  [27 38]   [3 43]      [9 82]   [10]
            \       /             \      /
          [3 27 38 43]           [9 10 82]
                 \                  /
              [3 9 10 27 38 43 82]

Analysis

Each level of the recursion merges a total of n elements (O(n) work), and halving gives log2 n levels:

T(n) = 2T(n/2) + cn, T(1) = c

Unrolling: T(n) = 2k T(n/2k) + kcn. With 2k = n: T(n) = cn + cn log2 n = O(n log n).

PropertyMerge sort
Best / average / worstO(n log n) - the split does not depend on the data
Extra spaceO(n) for the temporary array (plus O(log n) stack)
StableYes (take from the left half on ties)
In-placeNo (for arrays)

Merge sort on linked lists

For a linked list, merging just relinks nodes - no temporary array is needed - and the halves are found with a slow/fast pointer walk. Merge sort is therefore the standard way to sort linked lists in O(n log n) time and O(1) extra space (apart from recursion).

Iterative (bottom-up) merge sort

Merge runs of length 1 into runs of length 2, then 2 into 4, and so on, until one run remains. No recursion is needed; this is also how external merge sorts work.

3. Radix Sort (Distribution Sort)

Radix sort does not compare keys. It sorts integers digit by digit, starting from the least significant digit, using a stable distribution into 10 buckets (queues) for the digits 0-9.

PSEUDO
Algorithm RADIX_SORT(A, N, D)
// D = number of digits in the largest key
for POS ← 1 to D do                 // units, tens, hundreds, ...
    for each key X of A, in order, do
        append X to BUCKET[digit of X at POS]
    A ← BUCKET[0] + BUCKET[1] + … + BUCKET[9]   // collect in order
    empty all buckets

Example: 170 45 75 90 802 24 2 66

PassDigit usedArray after collecting
1units170 90 802 2 24 45 75 66
2tens802 2 24 45 66 170 75 90
3hundreds2 24 45 66 75 90 170 802

Complexity: O(d(n + k)) for d digits and base k (10 here) - linear in n when d is small. Extra space O(n + k); stable. It works only for keys that can be split into digits (integers, fixed-length strings).

4. Comparison of Sorting Algorithms

AlgorithmBestAverageWorstExtra spaceStableMethod
Bubble (with flag)O(n)O(n2)O(n2)O(1)YesExchange
SelectionO(n2)O(n2)O(n2)O(1)NoSelection
InsertionO(n)O(n2)O(n2)O(1)YesInsertion
Shell (Knuth gaps)O(n log n)about O(n1.25)O(n1.5)O(1)NoInsertion
HeapO(n log n)O(n log n)O(n log n)O(1)NoSelection
QuickO(n log n)O(n log n)O(n2)O(log n)NoExchange
MergeO(n log n)O(n log n)O(n log n)O(n)YesMerging
RadixO(d(n + k))O(d(n + k))O(d(n + k))O(n + k)YesDistribution

Which sort to use?

  • Small or nearly sorted data → insertion sort.
  • General in-memory sorting, fastest on average → quick sort (with a good pivot).
  • Guaranteed O(n log n) with no extra memory → heap sort.
  • Stability needed, linked lists, or data on disk → merge sort.
  • Many integer keys with few digits → radix sort.

Lower bound: any sort that only compares keys needs at least about n log2 n comparisons in the worst case (a decision tree with n! leaves has height at least log2 n!). Merge sort and heap sort meet this bound; radix sort beats it only because it does not compare keys.

💡 Tip

Key points to remember - Merge: two pointers, copy the smaller, O(m + n). - Merge sort: split in half, sort both, merge; T(n) = 2T(n/2) + n = O(n log n) in every case; stable; O(n) extra space. - Merge sort is the natural choice for linked lists and external sorting. - Radix sort: stable bucket passes from the least significant digit; O(d(n + k)). - Comparison sorts cannot beat O(n log n) in the worst case.

🎯 END-TERM EXAM PREP

📝 IPU End-Term Exam Corner (5-10 Marks)

  • Q1. Write the merge sort algorithm. Sort 38 27 43 3 9 82 10 showing each step. (10 Marks)
  • Write: MERGE and MERGE_SORT, the split/merge tree, and the merge comparison table.
  • Q2. Derive the time complexity of merge sort. Why is it preferred for linked lists? (5 Marks)
  • Write: the recurrence and its solution; relinking instead of copying, no random access needed.
  • Q3. Compare all sorting algorithms on best, average and worst case, space and stability. (7.5 Marks)
  • Q4. Explain radix sort with an example. (5 Marks)