-
merge sort
i am having a problem with the below problem of merge sort, i am not getting a desired ouput.
here is the program
Code:
/* sorting implementing the technique of merge sort */
# include<stdio.h>
# include<conio.h>
void mergesort(int *,int);
void main()
{
int x[20];int i,n;
clrscr();
printf("enter the number of elements of the array ");
scanf("%d",&n);
printf("enter the elemnts");
for(i=0;i<n;i++)
scanf("%d",&x[i]);
mergesort(x,n);
printf("the sorted elements are\n ");
for(i=0;i<n;i++)
{
printf("%d",x[i]);
printf("\n");
}
getch();
}
void mergesort(int x[],int n)
{
int aux[20],i,j,k,l1,l2,u1,u2;
int size=1;
while(size<n)
{
l1=0;
k=0;
while(l1+size<n)
{
l2=l1+size;
u2=l2-1;
u2=(l2+size-1)? 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++];
l2=u2+1;
}
for(i=l1;k<n;i++)
aux[k++]=x[i];
for(i=0;i<n;i++)
x[i]=aux[i];
size*=2;
}
}
every time the program runs,it intakes the values then getting out of the dos shell.
[code][/code]tagged by Salem
-
Few people will be able to understand this. Why don't you
just code it like this
Code:
void mergesort(int A[], int p, int r) {
if (p < r) {
int q = (r - p)/ 2;
mergesort(p, q);
mergesort(q + 1, r);
merge(A, p, q, r);
}
}
// merge the sorted A[p..q] with A[q + 1..r] to make
// a sorted A[p..r]
void merge(int A[], int p, int q, int r) {
// code for merge
}
-
Again, I agree- adapt his code to work with yours- do not reinvent the wheel.
-
int q = (r - p)/ 2;
This should be (r + p) / 2;