Merge Sort

Context: FIT1008_MOC · a Divide and Conquer sort · solves the Sorting Problem · uses an Auxiliary Function (Recursion) · contrast with Quick Sort · the merge step generalises from to lists in K-way Merge FIT2004 use: the merge is also an instrumentation point — threading a counter through it solves an apparently unrelated problem in Counting Inversions

Quick Revision

  • 🎯 Objective: cut in half, sort each, merge two sorted halves ➔ trivial-split / heavy-combine D&C sort.
  • 📦 Core Components: Split | Recurse ➔ two calls on | Merge, ties left-first ⇒ stable.
  • ⚡ Key Constraint: guaranteed every case + stable ➔ but needs scratch.

📝 Core

1. The Algorithm (Split → Merge)

  • Trivial split ➔ cut the array in half (card-pile metaphor).
  • Non-trivial combinemerge two already-sorted halves into one.
  • Apparatus ➔ one reused temp array of size + start/end markers; base case = 1-element slice.

2. Why Every Case

  • Level count ➔ halving ➔ levels.
  • Per-level work ➔ merge does total per level ➔ .
  • Order-independent ➔ best = average = worst; no case unlike Quick Sort.

3. Stability & Variants

  • Stable tie-break ➔ take from left half (<=) ➔ earlier-input keys emitted first.
  • Linked variantLinkList merges by relinking stack, no scratch.
  • External sort ➔ sequential access pattern ➔ basis of multiway sorts for data RAM.

⚙️ Core Implementation

🔹 merge_sort + auxiliary recursion + the merge

⚖️ Core Decision Matrix

(complexity table — Best / Average / Worst Time, Space, Stability.)

AlgorithmBestAverageWorstSpaceStableTrait
Merge SortYesguaranteed + stable, scratch array
Quick SortNoin-place, smaller constant
HeapsortNoin-place + guaranteed

When It Flips: merge sort's space/stability trade is the inverse of quicksort's — pick merge for worst-case guarantees, stability, linked lists, or external data; quicksort when in-place + smaller constant outweigh the risk.

📊 Exam Execution Trace

Manual Execution Trace

Merge of two sorted halves [2, 5] + [1, 4]:

Step / StateTrigger Opa[ia]a[ib]Taketmp Payload
0 (Init)init21[]
1compare21right (1<2)[1]
2compare24left (2≤4)[1,2]
3compare54right (4<5)[1,2,4]
4drain5left[1,2,4,5]

Applied Exercise

Problem: Derive merge sort’s complexity and show why it has no bad case. Derivation Proof / Hand-Calculation Walkthrough:

Final Extracted Output: best = average = worst = — no input degrades it.

🧠 Active Recall