有人能告诉我我的合并排序有什么问题吗?
有人可以告诉我下面的合并排序实现有什么问题吗?我已经挠头好几个小时了..
void merge(int arr[], int low, int mid, int high)
{
int i = 0;
int j = 0;
int k = 0;
int buf1[1024];
int buf1Length = mid - low + 1;
int buf2[1024];
int buf2Length = high - (mid + 1) + 1;
for (i = low; i <= mid; i++)
{
buf1[j++] = arr[i];
}
for (i = mid + 1; i <= high; i++)
{
buf2[k++] = arr[i];
}
i = 0;
j = 0;
k = 0;
while (j < buf1Length && k < buf2Length)
{
if (buf1[j] <= buf2[k])
{
arr[i++] = buf1[j++];
}
else
{
arr[i++] = buf2[k++];
}
}
while (j < buf1Length)
arr[i++] = buf1[j++];
while (k < buf2Length)
arr[i++] = buf2[k++];
}
void mergeSort(int arr[], int low, int high)
{
int mid;
if (low < high)
{
mid = (low + high) / 2;
mergeSort(arr, low, mid);
mergeSort(arr, mid + 1, high);
merge(arr, low, mid, high);
}
}
int main()
{
int i;
int arr[] = {6, 7, 2, 4, 9, 8};
mergeSort(arr, 0, 5);
printf("\n\n results: \n");
for (i = 0; i < 6; i++)
{
printf("%d ", arr[i]);
}
printf("\n\n\n");
return 0;
}
Can someone tell me what's wrong with my mergesort implementation below? I've been scratching my head for hours..
void merge(int arr[], int low, int mid, int high)
{
int i = 0;
int j = 0;
int k = 0;
int buf1[1024];
int buf1Length = mid - low + 1;
int buf2[1024];
int buf2Length = high - (mid + 1) + 1;
for (i = low; i <= mid; i++)
{
buf1[j++] = arr[i];
}
for (i = mid + 1; i <= high; i++)
{
buf2[k++] = arr[i];
}
i = 0;
j = 0;
k = 0;
while (j < buf1Length && k < buf2Length)
{
if (buf1[j] <= buf2[k])
{
arr[i++] = buf1[j++];
}
else
{
arr[i++] = buf2[k++];
}
}
while (j < buf1Length)
arr[i++] = buf1[j++];
while (k < buf2Length)
arr[i++] = buf2[k++];
}
void mergeSort(int arr[], int low, int high)
{
int mid;
if (low < high)
{
mid = (low + high) / 2;
mergeSort(arr, low, mid);
mergeSort(arr, mid + 1, high);
merge(arr, low, mid, high);
}
}
int main()
{
int i;
int arr[] = {6, 7, 2, 4, 9, 8};
mergeSort(arr, 0, 5);
printf("\n\n results: \n");
for (i = 0; i < 6; i++)
{
printf("%d ", arr[i]);
}
printf("\n\n\n");
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您确定要这样做吗:
?
乍一看,我觉得应该是:
Are you sure you want to be doing this:
?
At first glance, I think it should be:
合并排序必须合并已排序的子序列:
您不对任何子序列进行排序。
Mergesort must merge sorted subsequences:
You are not sorting any subsequence.
毫无疑问,问题出在您的
merge()
函数中。我想合并函数会像这样(这里的任何错误都留给读者:X ...这是未经测试的,即兴的,应该仅用于概念目的!):
The problem is without a doubt in your
merge()
function.I would imagine a merge function would go like this (any bugs in here are left to the reader :X ... this is untested and off the cuff, and should be used for conceptual purposes only! ):