Tuesday, August 25, 2009

merge sort

#include"stdio.h"
#include"conio.h"
void merge1(int a[],int first,int last);
void merge(int a[],int f1,int l1,int f2,int l2);
int i,j,temp,a[20],n,pivot;
void main()
{
clrscr();
printf("ENTER THE LIMIT\n");
scanf("%d",&n);
printf("enter the nos for sorting\n");
for(i=0;in;i++)
scanf("%d",&a[i]);

for(i=0;i<n;i++)
printf("%d",a[i]);


merge1(a,0,n-1);

printf("the sorted list\n");
for(j=0;j<n;j++)
printf("\n %d",a[j]);
getch();
}
void merge1(int a[],int first,int last)
{
int mid;
if(first<last)
{
mid=(first+last)/2;
merge1(a,first,mid);
merge1(a,mid+1,last);
merge(a,first,mid,mid+1,last);

}
}
void merge(int a[],int f1,int l1,int f2,int l2)
{
int b[20],i,j,k=0;
i=f1;
j=f2;
while(i<=l1&&j<=l2)
{
if(a[i]<a[j])
b[k]=a[i++];
else
b[k]=a[j++];
k++;
}
while(i<=l1)
b[k++]=a[i++];
while(j<=l2)
b[k++]=a[j++];
i=f1;
j=0;

while(i<=l2&&j<k)
a[i++]=b[j++];
}

No comments:

Post a Comment