Friday, 12 September 2014

MERGE SORT


main()
{
int A[]={3,1,9,8,0,2,99,77};
int min=0;
int max=7;
merge(A,min,max);
int i;
for(i=0;i<=7;i++)
{
printf("%d\n",A[i]);
}
}
void merge(int A[],int min,int max)
{
if(min==max){return;}
int mid=(min+max)/2;
merge(A,min,mid);
merge(A,mid+1,max);
mergesort(A,min,mid,max);
}
void mergesort(int A[],int min,int mid,int max)
{
int i,j,k;
int res[max-min];
for(i=min,j=mid+1,k=0;i<=mid&&j<=max;)
{
if(A[i]<A[j])
{
res[k]=A[i];
i++;
}
else
{
    res[k]=A[j];
j++;
}
k++;
}
while(i<=mid)
{
res[k]=A[i];
k++;i++;
}
while(j<=max)
{
res[k]=A[j];
k++;
j++;
}
for(i=min;i<=max;i++)
{
A[i]=res[i-min];

}
}

No comments:

Post a Comment