C : Mergesort - what is the mistake? Wrong output (repetition)
I have written this "mergesort" in C. I think somewhere there is mistake in copying back the elements to original array. can someone help me?
Huge lots of thanks in advance.
enter code here
/*************************** Merge sort ********************************/
#include <stdio.h>
void merge(int arr[], int start1, int end1, int start2, int end2)
{
int temp[100], beg1, beg2, i;
beg1=start1;
beg2=start2;
i=0;
while((beg1<=end1)&&(beg2<=end2))
{
if(arr[beg1]<arr[beg2])
{
temp[i++]=ar开发者_如何学JAVAr[beg1++];
}
else
{
temp[i++]=arr[beg2++];
}
}
if(beg1<end1) {
while(beg1<=end1) temp[i++]=arr[beg1++];
}
if(beg2<end2) {
while(beg2<=end2) temp[i++]=arr[beg2++];
}
i=0;
for(beg1=start1; beg1<=end1; beg1++)
{
arr[beg1]=temp[i++];
}
for(beg1=start2; beg1<=end2; beg1++)
{
arr[beg1]=temp[i++];
}
}
void mergesort(int arr[], int beg, int end)
{
int mid;
if(beg<end) {
mid=(beg + end)/2;
mergesort(arr, beg, mid);
mergesort(arr, mid+1, end);
merge(arr, beg, mid, mid+1, end);
}
}
int main()
{
int i;
int arr[]={34, 3, 10, 78, 4, 0, 14};
mergesort(arr, 0, 6);
printf("Here are the sorted elements:\n");
for(i=0; i<6; i++){
printf("%d\t",arr[i]);
}
printf("\n");
}
Output:
[root@dhcppc0 sorting]# gcc mergesort.c
[root@dhcppc0 sorting]# ./a.out
Here are the sorted elements:
0 0 3 0 10 10
end1
and end2
are valid indices, so I don't think yo should have those if
statements here
if(beg1<end1) {
while(beg1<=end1) temp[i++]=arr[beg1++];
}
if(beg2<end2) {
while(beg2<=end2) temp[i++]=arr[beg2++];
}
what if beg1
== end1
?
if beg1<end1
, you have at least 2 array elements left in the range [beg1, end1]. If there is only one, you should copy it too. You should leave the loops unguarded by the if statements. Change the code presented above to:
//if(beg1<end1) {
while(beg1<=end1) temp[i++]=arr[beg1++];
//}
//if(beg2<end2) {
while(beg2<=end2) temp[i++]=arr[beg2++];
//}
On a side note, your sort is not stable. To fix it, change this condition
if(arr[beg1]<arr[beg2])
to
if(!(arr[beg2]<arr[beg1]))
精彩评论