next up previous
Next: Analyzing Divide-and-Conquer Algorithms Up: l1 Previous: Example: Merge Sort

Example: Merge Sort

Merge(A,p,q,r) procedure has $\Theta(n)$ running time, n = r - p + 1

Merge(A,p,q,r) $\;\;\;\;\;$$\;\;\;\;\;$$\;\;\;\;\;$; Exercise 1.3-2
$\,$1 $\;\;\;\;\;$for j = p to r
$\,$2 $\;\;\;\;\;$$\;\;\;\;\;$B[j] = A[j]
$\,$3 $\;\;\;\;\;$i = p
$\,$4 $\;\;\;\;\;$w = q + 1
$\,$5 $\;\;\;\;\;$while (p $\leq$ q) and (w $\leq$ r)
$\,$6 $\;\;\;\;\;$$\;\;\;\;\;$if B[p] $\leq$ B[w]
$\,$7 $\;\;\;\;\;$$\;\;\;\;\;$then A[i] = B[p]
$\,$8 $\;\;\;\;\;$$\;\;\;\;\;$$\;\;\;\;\;$p = p + 1
$\,$9 $\;\;\;\;\;$$\;\;\;\;\;$else A[i] = B[w]
10 $\;\;\;\;\;$$\;\;\;\;\;$$\;\;\;\;\;$w = w + 1
11 $\;\;\;\;\;$$\;\;\;\;\;$i = i + 1
12 $\;\;\;\;\;$if p $>$ q
13 $\;\;\;\;\;$then p = w
14 $\;\;\;\;\;$$\;\;\;\;\;$q = r
15 $\;\;\;\;\;$for j = p to q
16 $\;\;\;\;\;$$\;\;\;\;\;$A[i] = B[j]
17 $\;\;\;\;\;$$\;\;\;\;\;$i = i + 1



MergeSort



Compare sorting algorithms


next up previous
Next: Analyzing Divide-and-Conquer Algorithms Up: l1 Previous: Example: Merge Sort