麦克海普给出错误的结果
我编写了以下代码以从已经存在的数组构建Maxheap的downdodjust函数使数组成为最大堆,但并未根据需要产生结果 请检查代码,告诉我我要在哪里出错,如果有人建议更改Downhodjust功能的哪些更改将有助于我制作最小的堆(这是我必须编码的下一个问题)
#include <iostream>
using namespace std;
void downadjust(int heap[],int i){
// n is size
int n=heap[0];
int j,flag=1;
while(2*i<=n && flag==1){
j=2*i;
if(j+1<=n && heap[j+1]>heap[j]){
j=j+1;
}
if(heap[i]>heap[j]) flag=0;
else
{
swap(heap[i],heap[j]);
i=j;
}
}
}
void disp(int heap[],int n){
for(int i=1;i<n;i++){
cout<<heap[i]<<" ";
}
}
int main()
{
int n;
cout<<"no of stud";
cin>>n;
n++;
int heap[n];
heap[0]=n-1;
for(int i=1;i<n;i++){
cin>>heap[i];
}
for(int i=n/2;i>=1;i--){
downadjust(heap,i);
}
disp(heap,n);
cout<<endl;
cout<<"max is "<<heap[1];
return 0;
}
I wrote the following code to build a maxheap from a already existing array the downadjust function makes the array a max heap but it is not producing results as desired
Please check the code and tell me where am I going wrong also it would be very helpful if someone suggest what changes to the downadjust function will help me in making a min heap ( that is the next question that I have to code)
#include <iostream>
using namespace std;
void downadjust(int heap[],int i){
// n is size
int n=heap[0];
int j,flag=1;
while(2*i<=n && flag==1){
j=2*i;
if(j+1<=n && heap[j+1]>heap[j]){
j=j+1;
}
if(heap[i]>heap[j]) flag=0;
else
{
swap(heap[i],heap[j]);
i=j;
}
}
}
void disp(int heap[],int n){
for(int i=1;i<n;i++){
cout<<heap[i]<<" ";
}
}
int main()
{
int n;
cout<<"no of stud";
cin>>n;
n++;
int heap[n];
heap[0]=n-1;
for(int i=1;i<n;i++){
cin>>heap[i];
}
for(int i=n/2;i>=1;i--){
downadjust(heap,i);
}
disp(heap,n);
cout<<endl;
cout<<"max is "<<heap[1];
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
5 1 9 2 11 50 6 100 7
的结果有效堆100 11 50 7 5 9 6 2 1
。也许您想要
50 11
序列和其他有序的子节点对,但是堆的结构不能像二进制搜索树一样严格地相互订购(如二进制搜索树)。要使Minheap,您只需要更改两个比较:
Result for
5 1 9 2 11 50 6 100 7
is valid heap100 11 50 7 5 9 6 2 1
.Perhaps you wanted
50 11
sequence and other ordered pairs of child nodes, but heap construction does not provide strict mutual ordering of children (as binary search tree does).To make minheap, you just need to change two comparisons: