1. University MCA (AI/ML) Semester 2
  2. CAP7004
  3. Unit 3

CAP7004 · Unit 3: Searching and sorting

Merge sort and quick sort

8 practice questions

Key points

  • Merge sort: O(n log n) always, stable, O(n) extra space
  • Quick sort: average O(n log n), worst O(n^2), in place, unstable
  • Pivot choice decides quick sort balance
  • Python uses stable Timsort

Both are divide-and-conquer sorts that beat O(n^2).

Merge sort: split the list in half, sort each half recursively, then merge two sorted halves in O(n). Recurrence T(n) = 2T(n/2) + O(n), so O(n log n) in all cases. Needs O(n) extra space and is stable. Merging [1, 4, 7] and [2, 3, 9] gives [1, 2, 3, 4, 7, 9].

Quick sort: choose a pivot, partition so smaller items are on its left and larger on its right, then sort both sides recursively. Average O(n log n), in place (O(log n) stack), not stable. Worst case O(n^2) when partitions are very unbalanced, for example a sorted list with the last element as pivot (45 comparisons for n = 10). Random or median-of-three pivots avoid this.

Lomuto partition of [10, 80, 30, 90, 40, 50, 70] with pivot 70 (last): result [10, 30, 40, 50, 70, 90, 80], pivot index 4.

Python: sorted() and list.sort() use Timsort (merge + insertion hybrid): O(n log n) worst case, O(n) on already sorted data, stable. key= and reverse=True customise the order.

Exam pitfall: quick sort's average is O(n log n) but its worst case is O(n^2); merge sort is O(n log n) always.

Try two questions

Question 1 · Tier 2, Understand

Merging the sorted lists [1, 4, 7] and [2, 3, 9] gives:

  1. [1, 2, 4, 3, 7, 9]
  2. [1, 4, 7, 2, 3, 9]
  3. [1, 2, 3, 4, 7, 9]
  4. [9, 7, 4, 3, 2, 1]
Show the answer

C. The merge repeatedly takes the smaller front item.

Question 2 · Tier 3, Apply

After a Lomuto partition of [10, 80, 30, 90, 40, 50, 70] with the last element as pivot, the pivot's final index is:

  1. 5
  2. 3
  3. 6
  4. 4
Show the answer

D. Items <= 70 are 10, 30, 40, 50, so the pivot lands at index 4.