Lecture 15 recurrences 2: mergesort & quicksort Oct. 13,...
Transcript of Lecture 15 recurrences 2: mergesort & quicksort Oct. 13,...
Recall: Mergesort
2
810
311
617
16254
13
810
311
617
16254
13
1368
1011
2457
1316
12345678
10111316
mergesort
mergesort
mergepartition
3
mergesort(list){if list.length == 1
return listelse{
mid = (list.size - 1) / 2list1 = list.getElements(0,mid)list2 = list.getElements(mid+1, list.size-1)list1 = mergesort(list1)list2 = mergesort (list2)return merge( list1, list2 )
}} = + 2 2
4
= + +
What if is not even ?
e.g. 13 = ∗ 13 + 6 + 7In general, one should write the recurrence as:
round down round up
In COMP 250, one typically assumes = 2 for recurrences that involve ( ).The more general recurrence has roughly the same solution.
12
Recall this slide fromlecture 13:
Q: How manyoperations arerequired to mergesorta list of size ?A: ( )
13
mergesort(list){if list.length <= 4 // or some other base case
return slowSort(list) // see lecture 7else{
mid = (list.size - 1) / 2list1 = list.getElements(0,mid)list2 = list.getElements(mid+1, list.size-1)list1 = mergesort(list1)list2 = mergesort (list2)return merge( list1, list2 )
}} = + 2 2 , ≥ 5
17
if list.length <= 4return slowSort(list)
For large , this is thedominant term.
For large , this is notthe dominant term.
Quicksort
18
810
311
617
16254
13
3617254
10111613
12345678
10111316
quicksort
quicksort
partition
1234567
10111316
concatenate
pivot
Quicksort worst case example
19
110
811
637
16254
13
108
11637
16254
13
12345678
10111316
quicksort
quicksort
partition
concatenate
pivot
2345678
10111316
How to reduce the chances of worst case ?(unbalanced partition)
“Median of three” technique:
Let the pivot be themedian of first,middle, and last elements in list.
e.g. pivot = median( 1, 13, 4) = 4
0
(size-1)/2
size-1
110
811
613
716
2534
22
23
110
811
613
716
2534
0
(size-1)/2
size-1
123
108
116
137
165
4partition
Works well inpractice, especiallyif the list is alreadynearly sorted.
(Details omitted.)
pivot