Lecture 04 - Divide and Conquer
Lecture 04 - Divide and Conquer
Solving
Lecture 04 – Problem Solving
using Divide and Conquer
subproblem 1 subproblem 2
of size n/2 of size n/2
a solution to a solution to
subproblem 1 subproblem 2
• Searching
• Binary Search
A[i]p A[i]p
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
Quick Sort
Merge Sort
• Split array A[0..n-1] into about equal halves and make
copies of each half in arrays B and C
• Sort arrays B and C recursively
• Merge sorted arrays B and C into array A as follows:
• Repeat the following until no elements remain in one of the
arrays:
• compare the first elements in the remaining unprocessed
portions of the arrays
• copy the smaller of the two into A, while incrementing the index
indicating the unprocessed portion of that array
• Once all elements in one of the arrays are processed, copy
the remaining unprocessed elements from the other array
into A.
8 3 2 9 7 1 5 4
8 3 2 9 7 1 5 4
8 3 2 9 71 5 4
8 3 2 9 7 1 5 4
3 8 2 9 1 7 4 5
2 3 8 9 1 4 5 7
1 2 3 4 5 7 8 9
Merge Sort
Merge Sort
Binary Search Tree
• Binary tree is a divide-and-conquer ready structure!
• Classic traversals (preorder, inorder, postorder) .
• In the preorder traversal, the root is visited before
the left and right subtrees are visited (in that order).
• In the inorder traversal, the root is visited after
visiting its left subtree but before visiting the right
subtree.
• In the postorder traversal, the root is visited after
visiting the left and right subtrees (in that order).
Binary Search Tree
Large Integer
Multiplication
• Consider the problem of multiplying two (large) n-
digit integers represented by arrays of their digits
such as:
• A = 12345678901357986429
• B = 87654321284820912836