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

announcements
SMART_READER_LITE
LIVE PREVIEW

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


slide-1
SLIDE 1

Announcements –

PA1 available, due 01/28, 11:59p.

Today’s Plan – Another sorting algorithm Runtime of recursive algorithms Correctness of recursive algorithms

slide-2
SLIDE 2

Warm-up…

Task: Given an array where 1st and 2nd halves are sorted, return sorted array.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 void merge(vector<int> & A,int fir,int sec, int secsize){ int firsave = fir; int firend = sec; int secend = sec + secsize; vector<int> temp; while (fir < firend && sec < secend){ if (A[fir] < A[sec]) { temp.push_back(A[fir]); fir++;} else { temp.push_back(A[sec]); sec++;}} if (fir == firend){ while(sec != secend) {temp.push_back(A[sec]); sec++;}} else { while(fir != firend) {temp.push_back(A[fir]); fir++;}} for (int i = 0; i < temp.size(); i++) A[firsave+i] = temp[i]; }

1 4 6 7 2 3 5 8

Run time:

slide-3
SLIDE 3

New…

Task: sort this array…

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

slide-4
SLIDE 4

mergeSort

Task: sort this array

1 2 3 4 5 6 7 8 9 10 void mergeSort(vector<T> & A, int L, int R){ }

7 1 6 4 5 3 2 8

RT:

slide-5
SLIDE 5

Recurrences – self referential functions You know some already… A recurrence for mergeSort’s runtime:

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

slide-6
SLIDE 6

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

slide-7
SLIDE 7

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

slide-8
SLIDE 8

Correctness of Recursive functions:

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

7 1 6 4 5 3 2 8