堆与优先级队列

时间:2022-11-28 10:13:32
最大值堆(MAX-HEAP)的性质是任意一个结点的值都大于或者等于其任意一个子结点存储的值。由于根结点包含大于或等于其子结点的值,而其子结点又依次大于或者等于各自结点的值,所以根结点存储着该树的所有结点中的最大值。

最小值堆(MIN-HEAP)的性质是任意一个结点的值都小于或者等于其子结点存储的值。

无论最小值堆还是最大值堆,任何一个结点与其兄弟之间都没有必然的联系。

public class MaxHeap {

private Element[] heap;

private int maxSize;

private int size;

public MaxHeap(Element[] heap, int size, int maxSize) {
this.heap = heap;
this.size = size;
this.maxSize = maxSize;
}

public int size() {
return this.size;
}

public boolean isLeaf(int position) {
return (position >= size / 2) && (position < size);
}

public int leftChild(int position) {
return 2 * position + 1;
}

public int rightChild(int position) {
return 2 * position + 2;
}

public int parent(int position) {
return (position - 1) / 2;
}

public void buildheap() {
for (int i = size / 2; i >= 0; i--) {
siftdown(i);
}
}

private void siftdown(int position) {
while (!isLeaf(position)) {
int j = leftChild(position);
if ((j < (size - 1)) && (heap[j].getKey() < heap[j + 1].getKey())) {
j++;
}
if (heap[j].key >= heap[j + 1].getKey()) {
return;
}
swap(position, j);
position = j;
}
}

public void insert(Element element) {
int position = size++;
heap[position] = element;
while ((position != 0)
&& (heap[position].getKey() > heap[parent(position)].getKey())) {
swap(position, parent(position));
position = parent(position);
}
}

public Object removeMax() {
return remove(0);
}

public Object remove(int position) {
swap(position, --size);
if (size != 0) {
siftdown(position);
}
return heap[size];
}

private void swap(int src, int dest) {
Element element = heap[src];
heap[src] = heap[dest];
heap[dest] = element;
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

}

public class Element {
private Object value;

private int key;

public Element() {

}

public int getKey() {
return key;
}

public void setKey(int key) {
this.key = key;
}

public Object getValue() {
return value;
}

public void setValue(Object value) {
this.value = value;
}

}
}