The Divide-And-Conquer Paradigm
The Divide-And-Conquer Paradigm
• Merge sort:
• Divide the n-element sequence to be sorted into two n/2-element
sequence.
• Conquer: sort the subproblems, recursively using merge sort.
• Combine: merge the resulting two sorted n/2-element sequences.
Merge Sort: A Divide-and-Conquer Algorithm
MergeSort(A, p, r) T(n)
1. If p < r then (1)
2. q (p+r)/2 (1)
3. MergeSort (A, p, q) T(n/2)
4. MergeSort (A, q +1, r) T(n/2)
5. Merge(A, p, q, r) (n)
Recurrence: Analyzing Divide-and-Conquer Algorithms
• Describes a function recursively in terms of itself.
• Describes performance of recursive algorithms.
• Recurrence for a divide-and-conquer algorithms
(1), if n c
T (n)
aT (n / b) D ( n ) C ( n ),otherwise
• a: # of subproblems
• n/b: size of the subproblems
• D(n): time to divide the problem of size n into subproblems
• C(n): time to combine the subproblem solutions to get the answer for the problem
of size n
• Merge sort:
(1), if n c
T (n)
2T ( n / 2) ( n ),otherwise
• a = 2: two subproblems
• n/b = n/2: each subproblem has size n/2
• D(n) = (1): compute midpoint of array
• C(n) = (n): merging by scanning sorted subarrays
Solving Recurrences
• Time efficiency
• worst-case recurrence: T (n) = T(n/2 ) + 1, T (1) = 1
solution: T (n) = logn
This is VERY fast: e.g., T(106) = 20