Merge Sort
Merge Sort
Merge Sort
Merge sort is one of the most efficient sorting algorithms. It works on the principle
of Divide and Conquer.
In divide and conquer approach, the problem in hand, is divided into smaller sub
problems and then each problem is solved independently. When we keep on
dividing the subproblems into even smaller sub-problems, we may eventually
reach a stage where no more division is possible. Those "atomic" smallest
possible sub-problem (fractions) are solved. The solution of all sub-problems is
finally merged in order to obtain the solution of an original problem.
Algorithm
Merge sort keeps on dividing the array into equal halves until
it can no more be divided. By definition, if it is only one
element in the array, it is sorted. Then, merge sort combines
the smaller sorted arrays keeping the new array sorted too.
1 9 8 23 14 5 7 3
1 9 8 23 14 5 7 3
1 9 8 23 14 5 7 3
1 9 8 23 14 5 7 3
1 9 8 23 14 5 7 3
1 9 8 23
1 9 8 23 14 5 7 3
1 9 8 23 14 5 7 3
1 9 8 23 14 5 7 3
1 9 8 23 14 5 7 3
1 9 8 23 14 5 7 3
1 9 8 23 14 5 7 3
1 9
1 9 8 23 14 5 7 3
1 9 8 23 14 5 7 3
1 9 8 23 14 5 7 3
1 9 8 23
1 9 8 23 14 5 7 3
1 9 8 23 14 5 7 3
1 9 8 23 14 5 7 3
1 9 8 23 14 5
1 9 8 23 14 5 7 3
1 9 8 23 14 5 7 3
1 9 8 23 14 5 7 3
1 9 8 23 14 5 7 3
1 9 8 23 14 5 7 3
1 9 8 23 14 5 7 3
9 8 23 14 5 7 3
1
8 23 14 5 7 3
1 9
8 23 14 5 7 3
1 9
23 14 5 7 3
1 9 8
14 5 7 3
1 9 8 23
14 5 7 3
1 9 8 23
14 7 3
1 9 8 23 5
7 3
1 9 8 23 5 14
7 3
1 9 8 23 5 14
7
1 9 8 23 5 14 3
1 9 8 23 5 14 3 7
1 9 8 23 5 14 3 7
9 8 23 5 14 3 7
1
9 23 5 14 3 7
1 8
23 5 14 3 7
1 8 9
5 14 3 7
1 8 9 23
5 14 3 7
1 8 9 23
5 14 7
1 8 9 23 3
14 7
1 8 9 23 3 5
14
1 8 9 23 3 5 7
1 8 9 23 3 5 7 14
1 8 9 23 3 5 7 14
8 9 23 3 5 7 14
1
8 9 23 5 7 14
1 3
8 9 23 7 14
1 3 5
8 9 23 14
1 3 5 7
9 23 14
1 3 5 7 8
23 14
1 3 5 7 8 9
23
1 3 5 7 8 9 14
1 3 5 7 8 9 14 23
Code for Merge Sort
The merge sort involves two functions:-
T(n/2)
T(n/2)
c*n time
T(n)=c*n+2*(T(n/2))
RECURRENCE RELATION
T(n)=c*n+2*T(n/2)
RECURRENCE RELATION
T(n)=c*n+2*T(n/2)
T(n/2) = 2*T(n/4) + c*(n/2)
RECURRENCE RELATION
T(n)=c*n+2*T(n/2)
T(n/2) = 2*T(n/4) + c*(n/2)
T(n) = 2 [ 2*T(n/4) + c*(n/2) ] + c*n
T(n) = 4*T (n/4) + 2c*n
RECURRENCE RELATION
T(n)=c*n+2*T(n/2)
T(n/2) = 2*T(n/4) + c*(n/2)
T(n) = 2 [ 2*T(n/4) + c*(n/2) ] + c*n
T(n) = 4*T (n/4) + 2c*n
Similarly, T(n) = 8*T (n/8) + 3*c*n
RECURRENCE RELATION
T(n)=c*n+2*T(n/2)
T(n/2) = 2*T(n/4) + c*(n/2)
T(n) = 2 [ 2*T(n/4) + c*(n/2) ] + c*n
T(n) = 4*T (n/4) + 2c*n
Similarly, T(n) = 8*T (n/8) + 3*c*n
General T(n) = 2k * T(n/2k) + k*c*n
T(n) = 2k * T(n/2k) + k*c*n
If we consider n=2k ,Then k= log2n.
On substituting the values of n and k in the general equation
we get.