Please help me out. I am not able to get output for my quick sort programe. Code is given below
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
void merge(int arr[],int minm,int mid,int maxm)
{int i,j,l;
int t[maxm];
for(i=0,j=mid,l=0;i<mid||j<maxm;)
{
if(arr[i]<=arr[j])
{t[l]=arr[i];
l++;
i++;}
else
{t[l]=arr[j];
l++;
j++;}
}
if(i==mid)
for(;j<maxm;)
{
t[l]=arr[j];
l++;
j++;
}
if(j==maxm)
for(;i<maxm;)
{
t[l]=arr[i];
l++;
i++;
}
for(i=0;i<maxm;i++)
arr[i]=t[i];
}
void mergesort(int a[],int p,int n)
{int mid;
if(p<n)
{mid=(p+n)/2;
mergesort(a,p,mid);
mergesort(a,mid,n);
merge(a,p,mid,n);}
}
int main()
{int n,j;
printf("Enter the value of n");
scanf("%d",&n);
int a[n];
for(j=0;j<n;j++)
{ printf("Enter the value of n %d",j);
scanf("%d",&a[j]);
}
mergesort(a,0,n);
for(j=0;j<n;j++)
{ printf("The value of n %d is %d",j,a[j]);
}
return 1;
}
First of all, this is merge sort. Not quick sort.
Second, a programming tip: When you return something from the main, a success is indicated by returning 0
. All non-zero values are error indicators.
And third, your merge subroutine is all wrong. Consider the if(i==mid)
and if(j==maxm)
parts. These sections are used to copy remaining elements of either of the left or right sub-array to the temporary array t
. Suppose if i
is equal to mid
. That means, we need to copy remaining elements from the right sub-array. After this is done, if(j==maxm)
gets evaluated. But by virtue of the for
statement in the already executed if
, j
is equal to maxm
. So, what happens is the entire right sub-array will get copied once again. What you need here is else if(j==maxm)
(even a simple else
will work).
That is not it. In the very first for
statement, i
should start from minm
, not from 0
.
2 Likes
See this implementation of mergesort.
I hope it helps
1 Like
Hmm array starts from 0-n-1 so nice try but just work on the function merge() . I hope this may help you in some way…Good luck
1 Like
have a look at this implementation of merge sort it will help you
merge sort