Lec3, Algorithm Analysis & Design, Divide-and-Conquer
Lec3, Algorithm Analysis & Design, Divide-and-Conquer
Edited by
Dr/ Hossam Hawash
Basic algorithmic techniques
6 4 8 9 2 1 3
divide ✟✟
✟
✙
❍❍
❥
❍
6 4 8 9 2 1 3
divide ✄ ❅
❘
❅ ✠ ❅
❘
❅
✄ 4 8 9 2 1 3
✄
divide ✄✎ ☛✁ ❆❯ ☛✁ ❆❯ ☛✁ ❆❯
base case 6 4 8 9 2 1 3
merge ❈ ❆❯ ☛✁ ❆❯ ☛✁ ❆❯ ☛✁
❈ 4 8 2 9 1 3
❈
merge ❈❲ ✠ ❅
❘
❅ ✠
4 6 8 1 2 3 9
❍❍ ✟✟
merge ❥
❍ ✟
✙
1 2 3 4 6 8 9
Pseudocode for M ERGE -S ORT
M ERGE -S ORT(A, p, r)
M ERGE(A, p, q, r)
1 n1 = q − p 11 i = 1
2 n2 = r − q 12 j = 1
3 Create array L of size n1 + 1 13 for k = p to r − 1
4 Create array R of size n2 + 1 14 if L[i] ≤ R[j]
5 for i = 1 to n1 15 A[k] = L[i]
6 L[i] = A[p + i − 1] 16 i = i+1
7 for j = 1 to n2 17 else A[k] = R[j]
8 R[j] = A[q + j − 1] 18 j = j+1
9 L[n1 + 1] = ∞
10 R[n2 + 1] = ∞
Running time of M ERGE
The first two for loops take Θ(n1 + n2 ) = Θ(n) time, where
n = r − p.
The last for loop makes n iterations, each taking constant time, for
Θ(n) time.
Total time: Θ(n).
Remark
The test in line 14 is left-biased, which ensures that M ERGE -S ORT is
a stable sorting algorithm: if A[i] = A[j] and A[i] appears before A[j]
in the input array, then in the output array the element pointing to A[i]
appears to the left of the element pointing to A[j].
Characteristics of merge sort
The worst-case running time of M ERGE -S ORT is Θ(n log n), much
better that the worst-case running time of I NSERTION -S ORT, which
was Θ(n2 ).
(see next slides for the explicit analysis of M ERGE -S ORT).
M ERGE -S ORT is stable, because M ERGE is left-biased.
M ERGE and therefore M ERGE -S ORT is not in-place:
it requires Θ(n) extra space.
M ERGE -S ORT is not an online-algorithm: the whole array A must be
specified before the algorithm starts running.
Analysing divide-and-conquer algorithms [CLRS 2.3.2]
Guess. There is some constant a > 0 such that T (n) ≤ an lg n for all
n ≥ 2 that are powers of 2.
Let’s test it!
Solving the M ERGE -S ORT recurrence by guess-and-test
Test. For n = 2k , by induction on k.
Base case: k = 1
T (2) = 2c + 2d ≤ a 2 lg 2 if a ≥ c + d
= an′ lg n′ − an′ lg 2 + d n′
≤ an′ lg n′ if a ≥ d
T (n/2) T (n/2)
Second unfolding: for each size-n/2 subproblem, cost of f (n/2) plus cost
of two subproblems of size n/4 each.
f (n)
f (n/2) f (n/2)
f (n/2) f (n/2)
d′ n lg n + c n ≤ T (n) ≤ d n lg n + c n .
Theorem. Suppose