You are on page 1of 2

Mergesort

void merge(int a[], int l, int m, int r)


{
int i, j, k, b[size];

1
4
4
4

for(i=l, j=m+1, k=l; k<=r; k++){


if( i>m)
b[k]=a[j++];
else if( j>r)
b[k]=a[i++];
else if( a[i]<a[j])
b[k]=a[i++];
else
b[k]=a[j++];
}
for(i=l, i<r-l+1; i++)
a[i]=b[i];
}
}

33

11

55

77

90

40

60

11

33

11

33

44

9
9
9

10

11

12

22

88

66

55

11

33

44

77

90

55

77

90

55

77

90
40
60
40

60

9
9
9
9

11

22

33

40

44

55

22

40

60

66

6
0
7

22
66

88

22

66

88

66

88

99

88

90

99

void mergesort (int a[], int l, int r)


{
if(r > l)
{
int m=(l+ r)/2;
mergesort (a, l, m);
mergesort (a, m+1, r);
merge(a, l, m, r);
}
}

Analysis of mergesort
Let us assume that number of elements is two. We reason as follows to set the recurrence of T(n), the
worst-case running time of mergesort on n numbers. Mergesort on just one element takes constant time.
When n>1, there are three steps:
i)
ii)
iii)

Divide: the divide step just computes the middle of the subarray, which takes constant time.
Thus, D(n)=(1)
Conquer: we recursively solve, two subproblems, each of size n/2, which contributes 2T(n/2) to
the running time.
Combine: the merge procedure takes time (n), where n=r-l+1 is the number of elements merged.

Therefore the running time T(n) of mergesort is


(1)
T(n)=
2T(n/2)+ (n)= (nlgn)
Note: best case=worst case=average case= (nlgn)

You might also like