04 CS251 Devide and Conquer
04 CS251 Devide and Conquer
Divide-and-Conquer
3
Merge Sort
lo q hi
MERGE-SORT(A, p, r) 1 2 3 4 5 6 7 8 9 10 11
4 7 2 6 1 4 7 3 5 2 6
if lo < hi
4
Example –
1 2 3 4 5 6 7 8 9 10 11
4 7 2 6 1 4 7 3 5 2 6 q=6
Divide
1 2 3 4 5 6 7 8 9 10 11
q=3 4 7 2 6 1 4 7 3 5 2 6 q=9
1 2 3 4 5 6 7 8 9 10 11
4 7 2 6 1 4 7 3 5 2 6
1 2 3 4 5 6 7 8 9 10 11
4 7 2 6 1 4 7 3 5 2 6
1 2 4 5 7 8
4 7 6 1 7 3
5
Example – cont
1 2 3 4 5 6 7 8 9 10 11
Conquer 1 2 2 3 4 4 5 6 6 7 7
and
Merge
1 2 3 4 5 6 7 8 9 10 11
1 2 4 4 6 7 2 3 5 6 7
1 2 3 4 5 6 7 8 9 10 11
2 4 7 1 4 6 3 5 7 2 6
1 2 3 4 5 6 7 8 9 10 11
4 7 2 1 6 4 3 7 5 2 6
1 2 4 5 7 8
4 7 6 1 7 3
6
Analysis for Merge Sort
• Divide:
– compute q as the average of lo and hi: T(n) = (1)
• Conquer:
– recursively solve 2 sublists, each of size n/2 2T
(n/2)
• Combine:
– MERGE on an n-element subarray takes (n) time
C(n) = (n)
(1) if n =1
T(n) = 2T(n/2) + (n) if n > 1
7
Analysis for Merge Sort
Merge Sort Recurrence
T(n) = c if n = 1
2T(n/2) + cn if n > 1
• Conquer
– Recursively sort A[p..q] and A[q+1..r] using Quicksort
• Combine
– Trivial: the arrays are sorted in place
– No additional work is required to combine them
10
QUICKSORT
Quicksort(A, p, r)
if p < r then Initially: p=1, r=n
– q Partition(A, p, r)
– Quicksort(A, p, q − 1)
– Quicksort(A, q +1, r)
Recurrence:
T(n) = T(q) + T(n – q) + f(n) F(n) depends on PARTITION())
11
Partitioning
X X X
44 75 23 43 55 12 64 77 33
12 33 23 43 44 55 64 77 75
Example
q=5
q=3 q=6
Quicksort– worst case
• Worst-case partitioning
– One region has one element and the other has n – 1 elements
• Recurrence:
n n
T(n) = T(1) + T(n – 1) + n, 1 n-1 n
1 n-2 n-1
T(1) = (1)
n 1 n-3 n-2
T(n) = T(n – 1) + n 1
2 3
1 1 2
Recurrence:
T(n) = 2T(n/2) + (n)
Average Performance of Quicksort
• Average case
– On a random input array, we will have a mix of well balanced
and unbalanced splits
– Good and bad splits are randomly distributed across throughout
the tree
partitioning cost:
n partitioning cost: n n = (n)
1 n-1 2n-1 = (n)
(n – 1)/2 + 1 (n – 1)/2
(n – 1)/2 (n – 1)/2
19
Randomized version of quicksort
• Randomly selecting the pivot element will, on
average, cause the split of the input array to be
reasonably well balanced.
1. RANDOMIZED‐QUICKSORT(A, p, r)
2. if p < r
3. then q RANDOMIZED‐PARTITION(A, p, r)
4. RANDOMIZED‐QUICKSORT(A, p, q -1)
5. RANDOMIZED‐QUICKSORT(A, q + 1, r)
20