我撰寫了以下代碼來從已經存在的陣列構建一個 maxheap downadjust 函式使陣列成為一個最大堆,但它沒有產生預期的結果請檢查代碼并告訴我我哪里出錯了,如果有人建議對 downadjust 函式進行哪些更改將幫助我創建最小堆(這是我必須撰寫的下一個問題)
#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;
}
uj5u.com熱心網友回復:
結果5 1 9 2 11 50 6 100 7是有效的堆100 11 50 7 5 9 6 2 1。
也許您想要50 11序列和其他有序的子節點對,但堆構造不提供嚴格的子節點相互排序(就像二叉搜索樹一樣)。
要制作minheap,您只需要更改兩個比較:
if (j 1 <= n && heap[j 1] < heap[j]) {
j = j 1;
}
if (heap[i] < heap[j]) flag = 0;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/478405.html
