nextupprevious
Next:9.11 To Probe FurtherUp:9. Sorting MethodsPrevious:9.9 Radix Sorting

9.10 Merge Sort

Algorithm
 
 

list-type mergesort (list-type L; int n)

{

if (n = 1)

return (L)

else {

split L into two halves L1and L2;

return (merge (mergesort $ \left(\vphantom{L_1, \frac{n}{2}}\right.$L1,$ {\frac{n}{2}}$$ \left.\vphantom{L_1, \frac{n}{2}}\right)$, mergesort $ \left.\vphantom{\left(L_2, \frac{n}{2}\right)}\right.$$ \left(\vphantom{L_2, \frac{n}{2}}\right.$L2,$ {\frac{n}{2}}$$ \left.\vphantom{L_2, \frac{n}{2}}\right)$$ \left.\vphantom{\left(L_2, \frac{n}{2}\right)}\right)$

}

}
 

Let T(n) be the running time of mergesort on a list of size n. Then.

T(n) $\displaystyle \leq$ C1   (n = 1)
     
  $\displaystyle \leq$ $\displaystyle \underbrace{2T\left(\frac{n}{2}\right)}_{\begin{array}{l}\mbox{divide} \\\mbox{and} \\\mbox{conquer}\end{array}}^{}\,$$\displaystyle \underbrace{C_2n}_{\mbox{merge}}^{}\,$ (n > 1)  

It can be shown that T(n) is O(nlog n).

Mergesort as an External Sorting Procedure

Example

The following is organized into runs of length 3 with the tail having length 2.

7 15 29 8 11 13 16 22 31 5 12
Basic step

Consider two files f1 and f2 organized into runs of length k. Assume that

1.
If ni is the number of runs (including tails) of f1(i = 1, 2), then | n1 - n2$ \leq$ 1
2.
At most one of f1 and f2 has a tail
3.
The one with a tail (if any) has at least as many runs as the other.
In mergesort, we read one run from each of f1 and f2, merge the runs into a run of length 2k and append it to one of two files g1 and g2. By alternating between g1 and g2, these files would be organized into runs of length 2k, satisfying (1), (2), and (3).

Algorithm

Repeat ...

Example

f1 28 3 93 54 65 30 90 10 69 8 22
f2 31 5 96 85 9 39 13 8 77 10  
runs of length 1

$ \Downarrow$ merge into g1 and g2

g1 28 31 93 96 9 65 13 90 69 77 22
g2 3 5 54 85 30 39 8 10 8 10  
runs of length 2

$ \Downarrow$ merge into f1 and f2

f1 3 5 28 31 9 30 39 65 8 10 69 77
f2 54 85 93 96 8 10 13 90 22      
runs of length 4

$ \Downarrow$ merge into g1 and g2

g1 3 5 28 31 54 85 93 96 8 10 22 69 77
g2 8 9 10 13 30 39 65 90          
runs of length 8

$ \Downarrow$merge into f1 and f2

f1 3 5 8 9 10 13 28 30 31
  39 54 65 85 90 93 96    
                   
f2 8 10 22 69 77        
runs of length 16

$ \Downarrow$ merge into g1 and g2

g1 will be left with the sorted sequence

Multiway Mergesort
nextupprevious
Next:9.11 To Probe FurtherUp:9. Sorting MethodsPrevious:9.9 Radix Sorting
eEL,CSA_Dept,IISc,Bangalore