C program to sort using merge sort

This program demonstrates merge sort in C.  Merge sort is based on divide and conquer algorithm. In the best case merge sort makes O(n log n) or O(n) comparisons and in the worst case is makes O(n log n) comparisons. The first step in merge sort is to divide the input list into sub lists which contains only one element. Then the algorithm repeatedly merges the sub lists into sorted list until there is only one list. Merge sort can be either bottom up or top down implementation.


Program



//Merge Sort c progarm 

#include<stdio.h>

#include<conio.h>

#include<math.h>

void mergesort(int a[],int p,int q);

void merge(int a[],int p,int q,int r);

void main()

{

int n,a[10],i;

printf("Enter the size of the array: ");

scanf("%d",&n);

printf("Enter the elements\n");

for(i=0;i<n;i++)

scanf("%d",&a[i]);

mergesort(a,0,n-1);

printf("Array after sorting\n");

for(i=0;i<n;i++)

printf("%d ",a[i]);

getch();

}

void mergesort(int a[10],int p,int r)

{

int mid;

if(p<r)

{

mid=(floor(p+r))/2;

mergesort(a,p,mid);

mergesort(a,mid+1,r);

merge(a,p,mid,r);

}

}

void merge(int a[10],int p,int q,int r)

{

int i=p,j=q+1,k=p,b[10];

while((i<=q)&&(j<=r))

{

if(a[i]<=a[j])

b[k++]=a[i++];

else

b[k++]=a[j++];

}

while(i<=q)

b[k++]=a[i++];

while(j<=r)

b[k++]=a[j++];

for(k=p;k<=r;k++)

a[k]=b[k];

}


Output


c program for merge sort
Merge Sort