如何解决两个不同结果的二进制最大堆问题
我试图了解二进制堆,并且尝试实现最大二进制堆。以下是我编写的代码。
public class MaxBinaryHeap {
private int size;
int[] heap;
public MaxBinaryHeap(int size) {
this.size = size;
}
public static void main(String[] args) {
//creating a heap
MaxBinaryHeap binaryHeap = new MaxBinaryHeap(20);
//adding elements to heap array
binaryHeap.add(2);
binaryHeap.add(7);
binaryHeap.add(26);
binaryHeap.add(25);
binaryHeap.add(19);
binaryHeap.add(17);
binaryHeap.add(1);
binaryHeap.add(90);
binaryHeap.add(3);
binaryHeap.add(36);
//calling this method to reorganize the heap array
binaryHeap.heap();
}
private void heap() {
int size = heap.length;
System.out.println(Arrays.toString(heap));
for(int i=0;i<size;i++) {
//following is call to another heap method - commented
//heapify2(heap)
heapify(heap);
}
}
//method to add elements in heap array
private void add(int i) {
if(heap==null) {
heap = new int[1];
heap[0]=i;
}
else {
int[] arr = new int[heap.length+1];
for(int x=0;x<heap.length;x++) {
arr[x]=heap[x];
}
arr[heap.length]=i;
heap=arr;
}
}
//the sorting in this method starts from the beginning
private void heapify(int[] heap) {
int size = heap.length;
for(int i=0;i<(size/2);i++) {
int child1=2*i+1;
if(child1<size) {
if(heap[child1] > heap[i]) {
int temp = heap[i];
heap[i]=heap[child1];
heap[child1]=temp;
}
}
int child2=2*i+2;
if(child2<size) {
if(heap[child2] > heap[i]) {
int temp = heap[i];
heap[i]=heap[child2];
heap[child2]=temp;
}
}
}
System.out.println(Arrays.toString(heap));
}
//the sorting in this method starts from the end
private void heapify2(int[] heap) {
int size = heap.length;
for(int i=(size/2);i>-1;i--) {
int child1=2*i+1;
if(child1<size) {
if(heap[child1] > heap[i]) {
int temp = heap[i];
heap[i]=heap[child1];
heap[child1]=temp;
}
}
int child2=2*i+2;
if(child2<size) {
if(heap[child2] > heap[i]) {
int temp = heap[i];
heap[i]=heap[child2];
heap[child2]=temp;
}
}
}
System.out.println(Arrays.toString(heap));
}
}
这是我的问题,
-
我实际上需要调用堆方法多少次,在下面的方法中,我调用了heapify方法10次,相当于数组的大小,但是它在大约3-4次迭代中对数组进行了排序,所以调用heapify方法的最少次数。
private void heap() { int size = heap.length; System.out.println(Arrays.toString(heap)); //calling heapify method for(int i=0;i<size;i++) { heapify(heap); } }
-
Input: [2,7,26,25,19,17,1,90,3,36] Output:[90,36,2,19] 90 / \ 36 26 / \ / \ 7 25 17 1 / \ / 2 3 19
Input: [2,36]
Output:[90,19]
90
/ \
36 17
/ \ / \
25 26 7 1
/ \ /
2 3 19
这两个方法产生两个不同的二进制堆,我想知道它们是否正确,并且有更好的方法来构建堆。在此先感谢您的帮助。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。