【发布时间】:2011-02-06 04:52:28
【问题描述】:
我制作了这个程序来对数组进行排序。它工作正常,但它不会排序!请帮我找出我的逻辑中的错误。谢谢
[更新] 它能够工作!我只是按照下面的建议降低了 i、j 和 k。另外,从 i
#include <stdio.h>
#include <stdlib.h>
void mergesort(int[], int, int);
void merge(int [], int low, int mid, int hi); //function prototype
int main()
{
int arr[]={1,4,78,92,9};
mergesort(arr,0,5);
//after mergesort
for(int i=0; i<5; i++)
{
printf("%d, ", arr[i]);
}
system("pause");
return 0;
}
void mergesort(int aptr[], int low, int hi)
{
int mid =0;
int rightmax=0;
int leftmax=0;
if(low==hi)
{
return;
}
mid=(low+hi)/2;
mergesort(aptr, low, mid);
mergesort(aptr, mid+1, hi);
merge(aptr, low, mid, hi);
}
void merge(int aptr[], int low, int mid, int hi)
{
int j, i, k;
//copy contents of aptr to auxiliary b
for(i=low; i<=hi; i++)
{
bptr[i]=aptr[i];
}
// iterate through b as if they were still two arrays, lower and higher
//copy smaller elements first
i=low;
j=mid+1;
k=low;
while(i<= mid && j<=hi)
{
if(bptr[i]<=bptr[j])//<--put smaller element first
{
aptr[k++]=bptr[i++];
}
else
{
aptr[k++]=bptr[j++];
}
}
// copy back first half just in case
while(i<=mid)
{
aptr[k++]=bptr[i++];
}
}//function
【问题讨论】:
-
程序不排序怎么能正常工作? ;-)
-
@Billy:我同意你的牙套风格。感谢您的编辑。 :-)
-
@Cody:去Allman style! :) 说真的,尽管我通常不会乱用样式,除非发布的代码 缺少 任何一致的样式。不过,非常欢迎您进行编辑。
标签: c recursion merge logic mergesort