Merge sort is a sorting technique based on divide and conquer technique. With worst-case time complexity being Ο(n log n), it is one of the most respected algorithms.
Merge sort first divides the array into equal halves and then combines them in a sorted manner.
To understand merge sort, we take an unsorted array as the following −
We know that merge sort first divides the whole array iteratively into equal halves unless the atomic values are achieved. We see here that an array of 8 items is divided into two arrays of size 4.
This does not change the sequence of appearance of items in the original. Now we divide these two arrays into halves.
We further divide these arrays and we achieve atomic value which can no more be divided.
Now, we combine them in exactly the same manner as they were broken down. Please note the color codes given to these lists.
We first compare the element for each list and then combine them into another list in a sorted manner. We see that 14 and 33 are in sorted positions. We compare 27 and 10 and in the target list of 2 values we put 10 first, followed by 27. We change the order of 19 and 35 whereas 42 and 44 are placed sequentially.
In the next iteration of the combining phase, we compare lists of two data values, and merge them into a list of found data values placing all in a sorted order.
After the final merging, the list should look like this −
Now we should learn some programming aspects of merge sorting.
C code:
#include <stdio.h>
#include <stdlib.h>
void merg(int *a,int n)
{
int i,j,l,r;
for(i=0;i<n;i++)
printf("%d",a[i]);
printf("\n");
if(n<2)
return;
l=n/2;
r=n-l;
int *le=malloc(sizeof(int)*l);
int *ri=malloc(sizeof(int)*r);
for(i=0;i<l;i++)
le[i]=a[i];
for(i=l;i<n;i++)
ri[i-l]=a[i];
merg(le,l);
merg(ri,r);
mergee(le,l,ri,r,a,n);
}
void mergee(int *a,int l,int *b,int r,int *c,int n)
{
int i,j,k;
i=j=k=0;
while(i<l&&j<r)
{
if(a[i]<=b[j])
c[k++]=a[i++];
else
c[k++]=b[j++];
}
while(i<l)
c[k++]=a[i++];
while(j<r)
c[k++]=b[j++];
}
int dmain(int argc, char *argv[]) {
int *p,i,n;
scanf("%d",&n);
p=malloc(sizeof(int)*n);
for(i=0;i<n;i++)
scanf("%d",p+i);
merg(p,n);
for(i=0;i<n;i++)
printf("%d",*(p+i));
return 0;
}