Merge-sort:
It is a sorting technique that sequences data by continuously merging items in the list. Every single item in the original unordered list is merged with another, creating groups of two. Every two-item group is merged, creating groups of four and so on until there is one ordered list.
Source Code:
#include <stdio.h>
#include <stdlib.h>
int c[50];
void merge(int b[], int low,int mid,int high)
{
int i, j, k=low;
i = low;
j = mid+1;
while((i <= mid) && (j <= high)) //Comparing & inserting items in new ordered list
{
if(b[i] <= b[j])
c[k++] = b[i++];
else
c[k++] = b[j++];
}
while(i <= mid) //Inserting remaining items from 1st half in new list
c[k++] = b[i++];
while(j <= high) //Inserting remaining items from 2nd half in new list
c[k++] = b[j++];
for(k=low;k<=high;k++)
b[k] = c[k];
}
void mergesort(int a[], int low, int high)
{
int mid;
if(low<high)
{
mid = (low+high)/2;
mergesort(a,low,mid); //Dividing the list into two - 1st half
mergesort(a,mid+1,high); // 2nd half
merge(a,low,mid,high); //Merging the lists
}
}
int main()
{
int a[50], i, n;
double e,s,t;
printf("\nEnter the size of the array: ");
scanf("%d", &n);
srand(time(NULL));
for(i=1;i<=n;i++)
a[i] = rand()%50 +1;
printf("\nElements of the array are: ");
for(i=1;i<=n;i++)
printf("%d ", a[i]);
mergesort(a,1,n);
printf("\nThe sorted array is: ");
for(i=1;i<=n;i++)
printf("%d ", c[i]);
}
Sample Output: