UNIT 3 Divide and Conquer
UNIT 3 Divide and Conquer
a problem of size n
(instance)
subproblem 1 subproblem 2
of size n/2 of size n/2
a solution to a solution to
subproblem 1 subproblem 2
Merge Sort
Quick Sort
Binary Tree Traversals and related properties
Multiplication of two large integers
Strassen’s Matrix Multiplication
General Divide-and-Conquer Recurrence
T(n) = aT(n/b) + f (n) where f(n) (nd), d 0
8 3 2 9 7 1 5 4
The non-recursive
version of Mergesort
8 3 2 9 71 5 4 starts from merging
single elements into
8 3 2 9 7 1 5 4 sorted pairs.
3 8 2 9 1 7 4 5
2 3 8 9 1 4 5 7
1 2 3 4 5 7 8 9
Analysis of Mergesort
A[i]p A[i]p
Exchange the pivot with the last element in the first (i.e., )
subarray — the pivot is now in its final position
Sort the two subarrays recursively
Divide and Conquer
Partitioning Algorithm
or i > r
< or j = l
5 3 1 9 8 2 4 7
2 3 1 4 5 8 9 7
1 2 3 4 5 7 8 9
1 2 3 4 5 7 8 9
1 2 3 4 5 7 8 9
1 2 3 4 5 7 8 9
Analysis of Quicksort
Best case: split in the middle — Θ(n log n)
Worst case: sorted array! — Θ(n2) T(n) = T(n-1) + Θ(n)
Average case: random arrays — Θ(n log n)
Improvements:
• better pivot selection: median of three partitioning
• switch to insertion sort on small subfiles
• elimination of recursion
These combine to 20-25% improvement
ALGORITHM Height(T )
//Computes recursively the height of a binary tree
//Input: A binary tree T
//Output: The height of T
if T = ∅
return −1
else
return max{Height(Tlef t ), Height(Tright)} + 1
Leaf Count
ALGORITHM LeafCount(T )
//Computes recursively the number of leaves in a binary tree
//Input: A binary tree T
//Output: The leaf count of T
if (T!= NULL)
{
LeafCount(T->left);
if ((T->left == NULL) && (T->right == NULL))
{
count++;
}
LeafCount(T->right);
}
return count;
Time Complexity
The time complexity of Tree Traversal and Leaf count:
N
Ci , j ai ,k bk , j
Time analysis k 1
N N N
Thus T ( N ) c cN 3 O( N 3 )
i 1 j 1 k 1
Strassens’s Matrix Multiplication
Strassen showed that 2x2 matrix multiplication
can be accomplished in 7 multiplication and 18
additions or subtractions. .(2log27 =22.807)
A B = R
A0 A1 B0 B1 A0B0+A1B2 A0B1+A1B3
=
A2 A3 B2 B3 A2B0+A3B2 A2B1+A3B3
A B = R
a0 b0 = a0 b0
P1 = (A11+ A22)(B11+B22)
P2 = (A21 + A22) * B11 C11 = P1 + P4 - P5 + P7
P3 = A11 * (B12 - B22) C12 = P3 + P5
P4 = A22 * (B21 - B11) C21 = P2 + P4
P5 = (A11 + A12) * B22 C22 = P1 + P3 - P2 + P6
P6 = (A21 - A11) * (B11 + B12)
P7 = (A12 - A22) * (B21 + B22)
Comparison
C11 = P1 + P4 - P5 + P7
= A11 B11 + A11 B22 + A22 B11 + A22 B22 + A22 B21 – A22 B11 -
A11 B22 -A12 B22 + A12 B21 + A12 B22 – A22 B21 – A22 B22