MERGE SORT

Previous Next


Program

#include “ stdio.h “

#include “ conio.h “

void main()

{

int x[20],n,i;

clrscr();

printf("Merge sort\n");

printf("Enter the number of elements :");

scanf("%d",&n);

printf("Enter the elements\n");

for(i=0;i <>

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

mergesort(x,n);

printf("The sorted list is:\n");

for(i=0;i <>

printf("%d\n",x[i]);

getch();

}

mergesort(x,n)

int x[20],n;

{

int aux[10],i,j,k,l1,l2,size,u1,u2;

size=1;

while(size <>

{

l1=0;

k=0;

while(l1+size < n)

{

l2=l1+size;

u1=l2-1;

u2=(l2+size-1 < n) ? l2+size-1 : n-1;

for(i=l1,j=l2;i < =u1 && j < =u2; k++)

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

aux[k] = x[i++];

else

aux[k] = x[j++];

for(;i < =u1;k++)

aux[k]=x[i++];

for(;j < =u2;k++)

aux[k]=x[j++];

l1=u2+1;

}

for(i=l1;k <>

aux[k++] = x[i];

for(i=0;i <>

x[i] = aux[i];

size*=2;

}

}