announcements
play

Announcements PA1 available, due 01/28, 11:59p. Todays Plan - PowerPoint PPT Presentation

Announcements PA1 available, due 01/28, 11:59p. Todays Plan Another sorting algorithm Runtime of recursive algorithms Correctness of recursive algorithms Warm-up Task: Given an array where 1 st and 2 nd halves are sorted, return


  1. Announcements – PA1 available, due 01/28, 11:59p. Today’s Plan – Another sorting algorithm Runtime of recursive algorithms Correctness of recursive algorithms

  2. Warm-up… Task: Given an array where 1 st and 2 nd halves are sorted, return sorted array. 1 4 6 7 2 3 5 8 1 void merge(vector<int> & A,int fir,int sec, int secsize){ 2 int firsave = fir; int firend = sec; int secend = sec + secsize; 3 vector<int> temp; 4 while (fir < firend && sec < secend){ 5 if (A[fir] < A[sec]) { 6 temp.push_back(A[fir]); fir++;} 7 else { 8 temp.push_back(A[sec]); sec++;}} 9 if (fir == firend){ 10 while(sec != secend) {temp.push_back(A[sec]); sec++;}} 11 else { 12 while(fir != firend) {temp.push_back(A[fir]); fir++;}} 13 for (int i = 0; i < temp.size(); i++) Run time: 14 A[firsave+i] = temp[i]; 15 }

  3. New… Task: sort this array… 7 1 6 4 5 3 2 8 7 1 6 4 5 3 2 8 2 3 5 8 1 4 6 7 1 2 3 4 5 6 7 8

  4. mergeSort Task: sort this array 7 1 6 4 5 3 2 8 1 void mergeSort(vector<T> & A, int L, int R){ 2 3 4 5 6 7 8 9 10 } RT:

  5. Recurrences – self referential functions You know some already… A recurrence for mergeSort’s runtime: void mergeSort(vector<T> & A, int L, int R){ 1 if (R > L) { 2 int M = (R + L)/2; 3 mergeSort(A, L, M); 4 mergeSort(A, M+1, R); 5 merge(A, L, M+1, R-M); } 6 } 7

  6. Finding a closed form (two approaches, there are others): 1) Expand and generalize:

  7. Finding a closed form (two approaches, there are others): 2) Recursion Tree:

  8. Correctness of Recursive functions: 7 1 6 4 5 3 2 8 void mergeSort(vector<T> & A, int L, int R){ 1 2 if (R > L) { 3 int M = (R + L)/2; 4 mergeSort(A, L, M); mergeSort(A, M+1, R); 5 6 merge(A, L, M+1, R-M); } 7 }

Recommend


More recommend