Skip to main content
Prepared by:-
Sruti sen patra
Merge sort
Definition:-
Merge sort is one of the most efficient sorting algorithms. It works
on the principle of Divide and Conquer. Merge sort repeatedly
breaks down a list into several sub lists until each sub list consists
of a single element and merging those sub lists in a manner that
results into a sorted list.
Divide and conquer rule:-
A divide-and-conquer algorithm recursively breaks down a
problem into two or more sub-problems of the same or
related type, until these become simple enough to be solved
directly. The solutions to the sub-problems are then
combined to give a solution to the original problem.
Algorithm(divide)
Mergesort(A, lb , ub,)
{
If(lb < ub)
{
Mid = lb+ub/2
Mergesort (A,lb,mid);
Mergesort (A,mid+1,ub);
Merge (A,lb,mid,ub)
}
}
Algorithm(Merge)
Mergesort( A, lb , mid , ub)
{
i=lb;
J=mid +1;
K= lb;
While ( i<=mid && j<=ub)
{
If(a[i]<=a[j])
{
b[k]=a[i]
i++;
Algorithm(merge)
}
Else
b[k]=a[j] ;
J++;
}
K++;
}}
If(i>mid)
{ while (j< =ub)
B[k]=a[j];
J++;
K++;
Algorithm(merge)
}
Else
{
While (i<=mid)
B[k]=a[i];
i++;
K++;
}
}
For(k=lb; k <=ub ; k++)
{ a[k]= b[k];
}}
Time complexity:-
Merge Sort is a recursive algorithm and time
complexity can be expressed as following recurrence
relation.
T(n) = 2T(n/2) + n
 Recurrence tree method:-
Recursion Tree is another method for solving the recurrence
relations. A recursion tree is a tree where each node represents the cost
of a certain recursive sub-problem. We sum up the values in each node
to get the cost of the entire algorithm.
The solution of the above recurrence is O(nLogn). The list
of size N is divided into a max of Logn parts, and the
merging of all sublists into a single list takes O(N) time, the
worst-case run time of this algorithm is O(nLogn)
Best Case Time Complexity: O(n*log n)
Worst Case Time Complexity: O(n*log n)
Average Time Complexity: O(n*log n)
The time complexity of MergeSort is O(n*Log n) in all the 3
cases (worst, average and best) as the mergesort always
divides the array into two halves and takes linear time to
merge two halves.
Merge sort algorithm