gpt4 book ai didi

java - 构建自下而上的堆

转载 作者:太空宇宙 更新时间:2023-11-04 14:58:09 28 4
gpt4 key购买 nike

我试图从我的教科书中的 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


}

最佳答案

Java 中的数组从索引 0 开始,到 n-1(而不是伪代码中的 1 到 n)。您正确地将 n 初始化为 array.length-1,但是您还应该使 for 循环继续 while i >= 0 而不是 i >= 1 。我没有运行您的程序来查看是否存在其他问题,但这似乎是首先要解决的问题。

关于java - 构建自下而上的堆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22948762/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com