C 中的堆排序,索引 0 问题
对于学校项目,我决定通过编写 HeapSort 来解决问题,但我有一个问题。 (“向量”是要排序的向量,“n”是“向量”中的元素数量)
这是我的代码:
void fixHeap(int position,int length)
{
int next=2*position;
int temp;
while (next<=length)
{
if (next<length && vector[next]<vector[next+1])
{
next++;
}
if (vector[position]<vector[next])
{
temp=vector[position];
vector[position]=vector[next];
vector[next]=temp;
position=next;
next=2*position;
}
else
{
return;
}
}
}
void heapSort()
{
int counter;
int temp;
for(counter=(n-1)/2;counter!=0;counter--)
{
fixHeap(counter,n-1);
}
for(counter=n-1;counter>0;counter--)
{
temp=vector[counter];
vector[counter]=vector[0];
vector[0]=temp;
fixHeap(0,counter-1);
}
display();
}
当我执行 fixHeap(0,n-1) 时,我将 0 放在旁边,然后位置也为 0,所以我并没有真正正确地处理堆。有人可以帮我修复它吗?
还有其他你发现但我可能忽略的错误吗?
for a project for school I have decided to solve a problem by coding a HeapSort but I have an issue. ("vector" is the vector to sort and "n" is the number of elements in "vector")
Here is my code :
void fixHeap(int position,int length)
{
int next=2*position;
int temp;
while (next<=length)
{
if (next<length && vector[next]<vector[next+1])
{
next++;
}
if (vector[position]<vector[next])
{
temp=vector[position];
vector[position]=vector[next];
vector[next]=temp;
position=next;
next=2*position;
}
else
{
return;
}
}
}
void heapSort()
{
int counter;
int temp;
for(counter=(n-1)/2;counter!=0;counter--)
{
fixHeap(counter,n-1);
}
for(counter=n-1;counter>0;counter--)
{
temp=vector[counter];
vector[counter]=vector[0];
vector[0]=temp;
fixHeap(0,counter-1);
}
display();
}
When I'm doing fixHeap(0,n-1) I'm putting next to 0 and then position is also at 0 so I'm not really doing the Heap right. Could someone help me fixing it?
Also are there other mistakes that you spotted that I may have overlooked?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
第 i 个节点的子节点位于 2*i 和 2*i+1 处。但是,如果您想对数组中的每个项目进行排序,第一个节点位于索引 0 处。您需要相应地修复子节点索引计算。
The children of the i-th node are are at 2*i and 2*i+1. But if you want to sort every item in the array, the 1st node is at index 0. You need to fix your child node index calculations accordingly.