Divide and Conquer Divide and Conquer: CS404/504 Computer Science 1 Design and Analysis of Algorithms: Lecture 8
Divide and Conquer Divide and Conquer: CS404/504 Computer Science 1 Design and Analysis of Algorithms: Lecture 8
Algorithm D-and-C(n: input size) if n n0 /* small size problem*/ Solve problem without futher sub-division; else Divide into m sub-problems; Conquer the sub-problems by solving them independently and recursively; /* D-and-C(n/k) */ Combine the solutions;
'
Suppose we divide the original problem into m sub-problems, each with a problem size n/k, and let D(n) be the time needed to do the dividing, and C(n) the time needed to do the combining. Then we got a very general formula to compute T(n):
T (n) =
& CS404/504
'
MERGE-SORT(A, p, r) {
if (p == r) /* small size */ return; else q = (p + r)/2; Merge-Sort(A, p, q); Merge-Sort(A, q+1, r); Merge(A, p, q, r);
}
To sort the whole array, Merge-Sort(A, 1, n) is called.
& CS404/504 %
'
Based on Master Method-Case 2, T (n) = (nlgn) for best, worst and average cases.
& CS404/504 %
'
Basic Steps: - Divide: split the array A[p..r] into two nonempty subarrays A[p..q] and A[q+1..r] such that each element of A[p..q] is less than or equal to each element of A[q+1..r]. - Conquer: Sort the two subarrays by calling quicksort recursively. - Combine: Trivial.
& CS404/504
'
QUICK-SORT(A, p, r)
if (p r) /* small size problem*/ return; else q := Partition(A, p, r); Quick-Sort(A, p, q-1); Quick-Sort(A, q+1, r);
& CS404/504
'
Partition Partition
- There are several dierent strategies that can be used by Partition. - One possible strategy: as we scan from left to right, we move the left bound to the right when the element is less than the pivot, otherwise we swap it with the rightmost unexplored element and move the right bound one step closer to the left. - Note: although the strategy used in CLRS textbook takes dierent form, it is essentially the same as the above.
& CS404/504
'
'
Divide: The divide step Partition takes linear time (n). Conquer: Recursively sort 2 subarrays, one with size q 1, the other is n q. C(n) = T (q 1) + T (n q). Combine: Basically no Combine step. T (n) = T (q 1) + T (n q) + (n).
& CS404/504
'
'
'
A case between the best and worst case A case between the best and worst case
'
Each possible pivot p is selected with equal probability. The number of comparisons needed to do the partition is n 1. 1 (T (q 1) + T (n q)) + n 1 n q=1
n n
T (n) =
2 T (n) = T (q 1) + n 1 n q=1
n
nT (n) = 2
q=1
& CS404/504
T (q 1) + n(n 1)
multiply by n
%
'
Contd Contd
n1
(n 1)T (n 1) = 2
q=1
T (q 1) + (n 1)(n 2)
apply to n 1
T (n1) 2(n1) + n(n+1) n T (n1) 2 2 + n+1 n(n+1) n T (n1) 2 + n+1 n T (n2) 2 2 + n + n+1 n1 T (n3) 2 2 2 + n1 + n + n+1 n2 T (1) 2 2 2 + 3 + 2 + ... + n + n+1 2 4 n+1 1 k=1 k
= ln (n + 1) + O(1)