Merge Sort
Announcements
Where we’re going
merge two sorted halves into one sorted array: \(\Theta(n)\).
Split in half, sort each half, merge. But how do the halves get sorted?
RT:
\(T(n) = 2\,T(n/2) + cn, \quad T(1) = b\)
Thm: \(\forall n \ge 1,\; T(n) \le cn\log n + bn.\)
Call mergeSort: mergeSort(A, 0, A.size()-1);
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);
merge(A, lo, mid, hi);
Conclusion:
To contemplate:
mid matter in the correctness proof?mid matter in the analysis of the runtime?| 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)\) |
CPSC 221