You are on page 1of 4

Experiment no: 4

Aim: To Analyze time complexity of Merge sort

CALCULATION OF COMPLEXITY :

Merge Sort:
Merge sort takes advantage of the ease of merging already sorted lists into a new
sorted list. It starts by comparing every two elements (i.e. 1 with 2, then 3 with 4...)
and swapping them if the first should come after the second. It when merges each of
the resulting lists of two into lists of four, then merges those lists of four, and so on;
until at last two lists are merged into the final sorted list. Of the algorithms described
here, this is the first that scales well to very large lists.

Merge sort works as follows:


1. Divide the unsorted list into two sub lists of about half the size
2. Sort each of the two sub lists
3. Merge the two sorted sub lists back into one sorted list.

Algorithm for Merge Sort:

merge(A,p,q,r)
{
n1=q-p+1 n2=rq
let
L[1......n1+1]
R[1......n2+1] be two new arrays.
for(i=1 to n1)
L[i]=A[p+i-1] for(j=1 to
n2)
R[j]=A[q+j]
L[n1+1]=infinity.(10000) R[n2+1]=infinity.(10000) i=1
j=1
for(k=p to r)
{
if(L[i]<=R[j])
{
A[k]=L[i]
i++
}
else
{
A[k]=R[j]
j++
}
}// end of for loop
} //end of function
merge_sort(A,p,r)
{ if(p<r)
{
q=(p+r)/2
merge_sort(A,p,q) merge_sort(A,q+1,r)
merge(A,p,q,r)
}
}The Recurrence Realtion for mergesort is
T(n) = 1 . . . if(n=1)
T(n) = 2 𝑻(𝒏) +n otherwise
𝟐
𝑛
By Master method, 𝑙

Here, a=2, b=2 f(n)=n 𝑜


𝑔
𝑎
𝑏
Now, we need to calculate, =

𝑛
𝑙 𝑜
𝑔
2

Therefore, 2

=
𝑛
T(n) = Ө(𝑓(𝑛) 𝑙𝑜𝑔2𝑛 ) 1

=
= Ө( 𝑛 𝑙𝑜𝑔2𝑛 ) 𝑛

i.e. T(n)=Ω(𝑛 𝑙𝑜𝑔2𝑛)


𝑛𝑙𝑜𝑔𝑎 𝑏 = 𝑓(𝑛)
Thus, the complexity of Merge Sort is linear logarithmic

Code:-
// Nishant Patil
// 9629 SE COMPS B
#include<stdio.h>
void merge(int a[],int low,int mid,int high)
{
int n1=mid-low+1;
int n2=high-mid;
int Left[n1],Right[n2];

for(int i=0;i<n1;i++)
{
Left[i]=a[i+low];
}
for(int j=0;j<n2;j++)
{
Right[j]=a[j+mid+1];
} int
i=0,j=0;
for(int
k=low;k<=hi
gh;k++)
{
if(i<n1 && j<n2)
{
if(Left[i]<=Right[j])
{
a[k]=Left[i];
i++; }
else {
a[k]=Right[j];
j++;
}
}
else if(j<n2)
{
a[k]=Right[j];
j++;
}
else if(i<n1)
{
a[k]=Left[i];
i++;
}
}
}
void mergeSort(int a[],int low,int high)
{
if(low<high)
{
int mid=(low+high)/2;
mergeSort(a,low,mid);
mergeSort(a,mid+1,high);
merge(a,low,mid,high);
}
}
int main()
{
int n;
printf("Enter the number of elements: ");
scanf("%d",&n);
int arr[n]; printf("Enter the
elements: ");
for(int i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}

mergeSort(arr,0,n-1); printf("The
Sorted elements are: "); for(int
i=0;i<n;i++)
{
printf("%d ",arr[i]);
}
return 0;
}
/***********************************************
Enter the number of elements: 5
Enter the elements: 2
9
3
8
4
The Sorted elements are: 2 3 4 8 9
***********************************************/

You might also like