EmbLogic's Blog

merge sort

/*Merge sort is a divide and conquer sorting technique in which we divide big problems into small i.e. in this we divide a big array into small arrays and after sorting these arrays we merge it and after merging it we get a sorted array.
At the time of doing this sorting technique i find some of the problems like garbage values and also segmentation faults so i tried to do this technique with a small array than after sometime i get my result*/
#include
void mergesort(int *,int ,int );
void merge(int *,int,int,int);
#define max 50
int main()
{
int merge[max],n,i,p=0;
printf(“enter no. of elements that you want to sort\n”);
scanf(“%d”,&n);
printf(“enter the elemrnts of array\n”);
for(i=0;i<n;i++)
scanf("%d",&merge[i]);
mergesort(merge, p, n-1);
printf("\n");
for(i=0;i<n;i++)
{
printf("a[%d]=%d\n",i,merge[i]);
}
return 0;
}
void mergesort(int* a,int p,int r)
{
int q;
if(p<r)
{
q=(p+r)/2;
mergesort(a,p,q);
mergesort(a,q+1,r);
merge(a,p,q,r);
}
}
void merge(int* a,int p,int q,int r)
{
int i=p,l=p,m=q+1,temp[max],k;
while(l<=q&&ma[m])
{
temp[i]=a[m];
m++;
}
else
{
temp[i]=a[l];
l++;
}
i++;
}
if(l>q)
{
for(i=i;iq temp[%d]=%d,a[%d]=%d\n”,i,temp[i],m,a[m]);
}
}
else
{
for(i=i;ir temp[%d]=%d,a[%d]=%d\n”,i,temp[i],l,a[l]);
}
}
for(i=p;i<=r;i++)
{
a[i]=temp[i];
printf("temp[%d]=%d,a[%d]=%d\n",i,temp[i],i,a[i]);
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>