Skip to content
GATEiit

GATE DA · Programming, Data Structures and Algorithms

Divide and conquer: merge sort and quicksort

Divide and conquer with recurrences, merge sort and quicksort: the merge and partition steps, comparison counts, best, average and worst cases, space, stability and how pivot choice decides quicksort's running time.

Before you start

  • Basic sorting →

    Gives the Θ(n2) baseline and the ideas of stability and in-place sorting.

  • Recursion in Python →

    Both algorithms are recursive; tracing them means following the call tree.

  • Logarithms and geometric series

    Recurrences are solved by summing work over log⁡n levels.

Concept notes

1. Divide and conquer and recurrences

A divide and conquer algorithm (1) divides the input into smaller subproblems, (2) conquers them recursively, and (3) combines their answers. Its running time is a recurrence: if it makes a calls on inputs of size n/b and spends f(n) dividing and combining, then T(n)=a T(n/b)+f(n).

Recursion tree method: level i has ai nodes of size n/bi. Add the work per level and sum over about log⁡bn levels.

Master theorem (compare f(n) with nlog⁡ba):

Case Condition T(n)
1 f(n)=O(nlog⁡ba−ϵ) Θ(nlog⁡ba)
2 f(n)=Θ(nlog⁡ba) Θ(nlog⁡balog⁡n)
3 f(n)=Ω(nlog⁡ba+ϵ) and regular Θ(f(n))

Common results:

  • T(n)=2T(n/2)+n → Θ(nlog⁡n) (merge sort, balanced quicksort).
  • T(n)=T(n/2)+1 → Θ(log⁡n) (binary search).
  • T(n)=T(n−1)+n → Θ(n2) (quicksort worst case).
  • T(n)=T(αn)+T((1−α)n)+n for a constant 0<α<1 → Θ(nlog⁡n), since each level still does at most n work and there are O(log⁡n) levels.

2. Merge sort

Merge sort splits the array into two halves, sorts each recursively, and merges the two sorted halves.

def merge(a, b):
    i = j = 0
    out = []
    while i < len(a) and j < len(b):
        if a[i] <= b[j]:
            out.append(a[i]); i += 1
        else:
            out.append(b[j]); j += 1
    return out + a[i:] + b[j:]

Merge cost: merging sorted lists of sizes m and k takes at least min⁡(m,k) comparisons (one list runs out first) and at most m+k−1 (they interleave to the end).

Running time: T(n)=2T(n/2)+Θ(n), so Θ(nlog⁡n) in the best, average and worst case. For n=2k, the worst-case number of comparisons is nlog⁡2n−n+1 (17 for n=8).

Properties:

  • Stable, because ties take from the left half (<=).
  • Not in-place on arrays: the merge needs Θ(n) extra space; the recursion depth is Θ(log⁡n).
  • Works well on linked lists (merge needs no extra array) and for external sorting of data on disk.

Bottom-up merge sort merges runs of size 1, 2, 4, … without recursion; after pass p every block of size 2p is sorted.

Split8 3 5 1 7 2 6 4Split8 3 5 17 2 6 4Split8 35 17 26 4Merge3 81 52 74 6Merge1 3 5 82 4 6 7Merge1 2 3 4 5 6 7 8log2 8 = 3 levels of merging, each level does at most n comparisons
Merge sort on [8, 3, 5, 1, 7, 2, 6, 4]: split down to single items, then merge back up

3. Quicksort and partitioning

Quicksort picks a pivot, partitions the array so that items ≤ pivot come before it and larger items after it, then sorts the two sides recursively. No combine step is needed.

Lomuto partition (pivot = last item):

def partition(a, lo, hi):
    p = a[hi]
    i = lo - 1
    for j in range(lo, hi):
        if a[j] <= p:
            i += 1
            a[i], a[j] = a[j], a[i]
    a[i + 1], a[hi] = a[hi], a[i + 1]
    return i + 1

It makes exactly n−1 comparisons on n items and puts the pivot in its final sorted position. Hoare partition scans from both ends and swaps out-of-place pairs; it usually makes fewer swaps but does not place the pivot at the split point.

Quicksort is in-place (only the recursion stack) and not stable: a partition swap can carry an item past an equal one.

After a partition, the pivot never moves again, so after k partition calls at least k items are in their final positions. Tracing questions often ask for the array after the first partition: follow the given code exactly, because Lomuto and Hoare give different arrays.

4. Quicksort: best, average and worst case

Quicksort's time depends on how evenly the pivot splits the array.

  • Best case: the pivot is always the median. T(n)=2T(n/2)+n=Θ(nlog⁡n).
  • Worst case: the pivot is always the smallest or largest item, leaving sides of size 0 and n−1. T(n)=T(n−1)+(n−1), which gives n(n−1)2 comparisons: Θ(n2). With first- or last-item pivots this happens on already sorted or reverse-sorted input, and on arrays of all-equal items with Lomuto.
  • Average case (random input, or random pivot): Θ(nlog⁡n), about 2nln⁡n≈1.39 nlog⁡2n comparisons.
  • Any constant-ratio split, even 1 : 99, still gives Θ(nlog⁡n).

Choosing the pivot at random, or as the median of three, makes the worst case very unlikely but not impossible. Using the true median (found in linear time) gives a guaranteed Θ(nlog⁡n), at a large constant cost.

Merge sort Quicksort
Best Θ(nlog⁡n) Θ(nlog⁡n)
Average Θ(nlog⁡n) Θ(nlog⁡n)
Worst Θ(nlog⁡n) Θ(n2)
Extra space Θ(n) O(log⁡n) average stack, O(n) worst
Stable Yes No
In-place No Yes

In practice quicksort is often faster because it works in place with good cache behaviour.

Formulas to remember

Divide and conquer recurrence
T(n)=a T(n/b)+f(n)
Merge sort
T(n)=2T(n/2)+Θ(n)=Θ(nlog⁡n)
Comparisons to merge sizes m and k
min⁡(m,k)≤C≤m+k−1
Merge sort worst-case comparisonsFor n a power of 2
nlog⁡2n−n+1
Quicksort worst case
T(n)=T(n−1)+(n−1)⇒n(n−1)2
Quicksort average comparisons
≈2nln⁡n≈1.39 nlog⁡2n

Common mistakes

  • Saying merge sort is Θ(n) in the best case; it always does Θ(nlog⁡n) work.
  • Assuming an unbalanced but constant-ratio split makes quicksort quadratic; only splits like 0 and n−1 do.
  • Mixing Lomuto and Hoare partitions when tracing; they give different arrays.
  • Calling quicksort stable, or merge sort in-place on arrays.
  • Using m+k instead of m+k−1 as the most comparisons in a merge.

Worked examples

Try each step yourself, then reveal the working.

Example 1: Counting comparisons in a merge

numerical

Merge [2, 5, 9, 14] and [3, 4, 10, 15, 20] with the merge function above. How many comparisons are made?

  1. Step 1: Compare the fronts until one list empties.

    Try it on paper first.

Example 2: Tracing a Lomuto partition

numerical

Apply the Lomuto partition (pivot = last item) to [7, 2, 9, 4, 3, 8, 5]. Give the array afterwards and the pivot's index.

  1. Step 1: Set the pivot and scan j = 0, 1.

    Try it on paper first.

Example 3: Worst case of quicksort

numerical

Quicksort with the last item as pivot (Lomuto) is run on the sorted array [1, 2, 3, 4, 5, 6]. How many comparisons does it make?

  1. Step 1: What does the first partition do?

    Try it on paper first.

Example 4: An unbalanced split is still n log n

conceptual

Suppose every partition splits the array in the ratio 1 : 9. Is quicksort still Θ(nlog⁡n)?

  1. Step 1: Draw the recursion tree.

    Try it on paper first.

Previous year questions

2 official GATE DA questions on this topic, newest first.

Practise these 2 PYQs →

Topic test

10 questions: up to 2 official PYQs and original practice questions, with GATE marking (MCQ wrong answers lose marks). Score 60% or more to pass. A new set is drawn each time.

Mark as mastered

Loading your progress…

My revision notes

Notes written by the GATEiit team against the official GATE DA syllabus; being checked by a reviewer. Updated 2026-11-21. Spotted a mistake? Use Report an issue on any question, or contact us.