我试图从我的课本中的 Psuedo 代码进行堆自下而上的构造,但是我得到的输出不是正确的堆,我正在退出 2 9 8 6 5 7
任何人都知道我哪里出错了(伪代码来自教科书,堆需要是数组)
这是我正在使用的 PsuedoCode 自下而上
//constructs a heap from elements of a given array by bottom up algorithm
//input an array H[1...n] of orderable items
//output a heap H[1...n]
for i<- [n/2] downto 1 do
k<-i; v<-H[k];
heap<-False
while not heap and 2*k <= n do
j<-2*k
if(j<n) //there are two children
if H[j] < H[j+1] j<- j+1
if v>=h[j]
heap = true
else H[k]<-H[j] k<-j
H[k] <-V
这是我的代码
package heapbottomup;
import javax.swing.Spring;
public class heapbottomup {
public static void main(String args[]){
int[] array = {2 ,9 ,7 ,6 ,5 ,8};
BottomUp(array);
}
static int[] BottomUp (int[]array){
int n = array.length-1;
for(int i=(n/2);i>=1;i--){
int k =i;
int v = array[k];
boolean Heap = false;
while(!Heap && ((2*k)<=n)){
int j = 2*k;
if (j<n){
if(array[j]<array[j+1]) j =j+1;
}
if(v>=array[j]){
Heap=true;
}
else{
array[k]= array[j];
k=j;
}
array[k]=v;
}//end while
}//end for
print(array);
return(array);
}
static void print(int[]array){
if(array==null){
System.out.println("empty");
return;
}
for(int i =0;i<array.length;i++){
System.out.print(array[i] + " ");
}
System.out.println();
}//end print
}