简体   繁体   English

Maxheap给出错误的结果

[英]Maxheap giving wrong result

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)我编写了以下代码来从已经存在的数组构建 maxheap 向下调整 function 使数组成为最大堆,但它没有产生所需的结果 请检查代码并告诉我我哪里出错了,如果有人建议对 downadjust function 进行哪些更改将帮助我制作最小堆(这是我必须编写的下一个问题)

#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;
}

Result for 5 1 9 2 11 50 6 100 7 is valid heap 100 11 50 7 5 9 6 2 1 . 5 1 9 2 11 50 6 100 7的结果是有效堆100 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).也许您想要50 11序列和其他有序的子节点对,但是堆构造不提供严格的子节点相互排序(就像二叉搜索树一样)。

To make minheap, you just need to change two comparisons:要制作minheap,您只需要更改两个比较:

 if (j + 1 <= n && heap[j + 1] < heap[j]) {
        j = j + 1;
    }
    if (heap[i] < heap[j]) flag = 0;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM