Reputation: 1439
I've got this merge sort implementation that doens't works and I can't figure why.
Here are the methods:
void merge_sort(int A[], int i, int j)
{
if(i<j)
{
int n = j-i+1;
int k = n/2;
merge_sort(A, i, i+k-1);
merge_sort(A, i+k, j);
merge(A, i, i+k, j);
}
}
And that's the merge method:
void merge(int A[], int a, int b, int j)
{
int* T = malloc(sizeof(int)*DIM);
int c=0;
int h=a;
while(a<b && b<=j)
{
if(A[a] > A[b])
T[c++] = A[a++];
else
T[c++] = A[b++];
}
while(a<b) T[c++] = A[a++];
while(b<=j) T[c++] = A[b++];
c=0;
while(h<=j)
A[h++] = T[c++];
}
Here is how I call merge_sort:
merge_sort(A, 0, DIM-1);
where DIM is the length of the array minus one.
That's the output:
5 2 4 6 8 9 7 1 3 10
0 9
0 4
0 1
2 4
3 4
5 9
5 6
7 9
8 9
10 9 8 7 10 6 5 4 3 2
The first half is perfectly ordered, the second half minus one also. I can't figure out where is the problem.
Upvotes: 0
Views: 88
Reputation: 9173
There are 2 problems with your code.
while
condition.Incorrect while
is here:
while(a<b && b<=j)
{
if(A[a] > A[b])
T[c++] = A[a++];
else
T[c++] = A[b++];
}
In this loop, you increase b
while it is in your condition too which will affect your loop.
Here is is your code that I corrected (i
in included in array while j
is excluded):
void merge_sort(int A[], int i, int j)
{
if(j-i>=2) // since j is excluded, this condition means that we have more than 1 member.
{
int k = (j+i)/2;
merge_sort(A, i, k);
merge_sort(A, k, j);
merge(A, i, k, j);
}
}
void merge(int A[], int a, int b, int j)
{
int* T = malloc(sizeof(int)*DIM);
int c=0;
int h=a;
int m = b;
while(a<b && m<j) // b and j are excluded
{
if(A[a] > A[m])
T[c++] = A[a++];
else
T[c++] = A[m++];
}
while(a<b) T[c++] = A[a++];
while(m<j) T[c++] = A[m++];
c=0;
while(h<j)
A[h++] = T[c++];
}
and run it with:
merge_sort(A, 0, DIM);
Upvotes: 1