<span style="font-size:32px;">package com.liebao34;
public class Heap {
private Node[] heapArr;
private int maxSize;
private int currentSize;
public Heap(int mx){
maxSize = mx;
currentSize = 0;
heapArr = new Node[maxSize];
}
public boolean isEmpty(){
return currentSize==0;
}
public boolean insert(int key){
if(currentSize==maxSize)
return false;
Node newNode = new Node(key);
heapArr[currentSize] = newNode;
trickleUp(currentSize);
currentSize++;
return true;
}
public void trickleUp(int index){
int parent = (index-1)/2;
Node bottom = heapArr[index];
while(index>0 && heapArr[parent].getKey()<bottom.getKey()){
heapArr[index] = heapArr[parent];
index = parent;
parent = (parent-1)/2;
}
heapArr[index] = bottom;
}
public Node remove(){
Node root = heapArr[0];
heapArr[0] = heapArr[--currentSize];
trickleDown(0);
return root;
}
public void trickleDown(int index){
int largeChild;
Node top = heapArr[index];
while(index<currentSize/2){
int leftChild = 2*index+1;
int rightChild = leftChild+1;
if(rightChild<currentSize&&heapArr[leftChild].getKey()<heapArr[rightChild].getKey()){
largeChild = rightChild;
}else{
largeChild = leftChild;
}
if(top.getKey()>=heapArr[largeChild].getKey())break;//no need to exchange
heapArr[index]=heapArr[largeChild];
index = largeChild;
}
heapArr[index] = top;
}
public boolean change(int
Heap的java实现
最新推荐文章于 2024-05-28 11:18:00 发布