CPSC 221

Merge Sort

Today

Announcements

  • Examlet 3 is this weekend, Thursday to Sunday
  • Next week is quiet: no class meetings, labs or examlets — two video lessons
  • Homework Two is due Monday 10/19


Where we’re going

  • Merge sort
  • Its running time, two ways
  • A proof of the closed form
  • Why it’s correct

Where we left off

7 1 6 4 5 3 2 8 7 1 6 4 5 3 2 8 1 4 6 7 2 3 5 8 1 2 3 4 5 6 7 8

merge two sorted halves into one sorted array: \(\Theta(n)\).

Split in half, sort each half, merge. But how do the halves get sorted?

mergeSort

  1. If the array has 0 or 1 elements, it’s sorted.
  2. Split the array into halves.
  3. Sort each half recursively.
  4. Merge the two halves.
void mergeSort(vector<T> & A, int lo, int hi) {
    if (hi > lo) {
        int mid = (hi + lo)/2;
        mergeSort(A, lo, mid);
        mergeSort(A, mid+1, hi);
        merge(A, lo, mid, hi);
    }
}

RT:

Closed form 1: expand and generalize

\(T(n) = 2\,T(n/2) + cn, \quad T(1) = b\)

Closed form 2: recursion tree

n n/2 n/2 n/4 n/4 n/4 n/4 ⋮ ⋮ ⋮ ⋮ work at this level number of levels:

Proving the closed form is correct:

Thm: \(\forall n \ge 1,\; T(n) \le cn\log n + bn.\)

MergeSort correctness:

Call mergeSort: mergeSort(A, 0, A.size()-1);

void mergeSort(vector<T> & A, int lo, int hi) {
    if (hi > lo) {
        int mid = (hi + lo)/2;
        mergeSort(A, lo, mid);
        mergeSort(A, mid+1, hi);
        merge(A, lo, mid, hi);
    }
}

Claim: mergeSort correctly sorts A[lo..hi] for any (hi-lo+1) ________

Let \(n\) = (hi - lo + 1), arbitrary.

\(n \le 1\): (Base Case)

\(n > 1\): IH: Assume mergeSort correctly sorts a slice of size \(j\), for any \(j < n\).

int mid = (hi + lo)/2;

mergeSort(A, lo, mid);
mergeSort(A, mid+1, hi);

MergeSort correctness, continued:

merge(A, lo, mid, hi);


Conclusion:



To contemplate:

  • does the value of mid matter in the correctness proof?
  • does the value of mid matter in the analysis of the runtime?
  • could we do a \(k\)-way merge sort?

Where are we in the sorting picture?

Best case Worst case
Insertion \(O(n)\) \(O(n^2)\)
Selection \(O(n^2)\) \(O(n^2)\)
Merge \(O(n\log n)\) \(O(n\log n)\)


https://www.toptal.com/developers/sorting-algorithms