Announcements: PA1 available, due 01/28, 11:59p. HW2 out soon, due 10/04, 11:59p. TODAY: Merge Sort, general sorting discussion A “divide and conquer” algorithm. 1. If the array has 0 or 1 elements, it’s sorted. Stop. 2. Split the array into two approximately equal-sized halves. 3. Sort each half recursively 4. Merge the sorted halves to produce one sorted result. void mergeSort(vector<T> & A, int lo, int hi){ 1 if (hi > lo) { 2 int mid = (hi + lo)/2; 3 mergeSort(A, lo, mid); 4 mergeSort(A, mid+1, hi); 5 merge(A, lo, mid, hi); } 6 } 7 RT:
Solving Recurrences Finding a closed form (two approaches, there are others): 1) Expand and generalize:
Finding a closed form (two approaches, there are others): 2) Recursion Tree:
Proving the closed form is correct: Thm: ∀𝑜 ≥ 1, 𝑈 𝑜 ≤ 𝑑𝑜 log 𝑜 + 𝑐𝑜.
MergeSort Correctness: 7 1 6 4 5 3 2 8 Call MergeSort: mergeSort(A, 0, A.size()-1); void mergeSort(vector<T> & A, int lo, int hi){ 1 if (hi > lo) { 2 int mid = (hi + lo)/2; 3 mergeSort(A, lo, mid); 4 mergeSort(A, mid+1, hi); 5 merge(A, lo, mid, hi); } 6 } 7
MergeSort Correctness continued: To contemplate: does the value of mid matter in the correctness proof? does the value of mid matter in the analysis of the runtime?
Where are we in the sorting picture? Average Best Case Worst Case Case Insertion Selection Merge https://www.toptal.com/developers/sorting-algorithms
Complexity of the Sorting Problem: The complexity of a problem is the runtime of the fastest algorithm for that problem. We'll only consider comparison-based algorithms. They can compare two array elements in constant time. They cannot manipulate array elements in any other way. For example, they cannot assume that the elements are numbers and perform arithmetic operations (like division) on them. Insertion, Merge, Quick, Radix, Selection
Recommend
More recommend