【发布时间】:2025-10-22 16:00:01
【问题描述】:
我正在根据 CLRS 在 C 中实现堆排序算法。但是我无法获得排序的输出。你能看看我的代码有什么问题吗?函数 maxheap 和 buildmaxheap 有效。我无法弄清楚代码有什么问题。
代码应该对数组元素进行堆排序。我觉得heapsort() 函数中有一个错误,因为maxheap 和buildmaxheap 工作得很好。
我得到的最终输出是
1 1 1 1 2 1 2 2 1 1
但预期的输出应该是
1 2 3 4 7 8 9 10 14 16
代码:
#include<stdlib.h>
#include<stdio.h>
#define maxn 11
int n=10;
int parent(int i)
{
return i/2;
}
int left(int i)
{
return 2*i+0;
}
int right(int i)
{
return 2*i+1+0;
}
void max_heap(int x[],int i,int heapsize)
{
int largest;
int l=left(i);
int r=right(i);
if (l<=heapsize && x[l]>x[i]){
largest=l;
}
else
{
largest=i;
}
if (r<=heapsize && x[r]>x[largest]){
largest=r;
}
if (largest!=i)
{
int s=x[i];x[i]=x[largest];x[largest]=s;
max_heap(x,largest,heapsize);
}
}
void buildmaxheap(int x[],int heapsize)
{
int i;
for(i=5;i>=1;i--)
max_heap(x,i,heapsize);
}
void heapsort(int x[])
{
buildmaxheap(x,10);
int i,t,heapsize=10;
for(i=10;i>=2;i--)
{
int s=x[i];x[1]=x[i];x[i]=s;
heapsize--;
/*
printf("%d",heapsize);
*/
max_heap(x,i,heapsize);
}
for(i=1;i<=10;i++)
printf("%d\t",x[i]);
}
int main()
{
int x[maxn],i;
x[1]=16;
x[2]=4;
x[3]=10;
x[4]=14;
x[5]=7;
x[6]=9;
x[7]=3;
x[8]=2;
x[9]=8;
x[10]=1;
heapsort(x);
/*
for(i=1;i<=10;i++)
printf("%d\t",x[i]);
*/
}
【问题讨论】:
-
究竟是什么不工作?
-
好吧,它浪费了 x[0]。开始。我不信任具有“1..”索引的 C 数组,即使声明的开头尺寸过大:(
-
堆排序函数。这是我在堆排序函数后打印数组后得到的输出:1 1 1 1 2 1 2 2 1 1
-
1.使用调试器。 2. C 中的数组是从零开始的,而不是从一开始的。不要逃避这个事实;拥抱它。 3. 具有堆属性potentially 的数组中索引
i处的元素在槽2*i+1和2*(i+1)有子元素,受整个序列长度N的限制(意味着如果那些计算为等于或大于N的值,则该孩子不存在)。 -
您需要在问题中添加更多详细信息,否则将作为题外话关闭:
Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers