最大值堆(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;
}
}
}
相关文章
- 【C++】大根堆(优先队列 priority_queue)与 小根堆
- RabbitMQ队列没有生成或者队列生成但是与交换机没有绑定成功解决办法
- 队列与链表
- 【Java学习笔记】45:优先级队列PriorityQueue和比较器Comparator
- Spring Boot 整合 RabbitMQ:注解声明队列与交换机详解
- 2016 - 1 -17 GCD主队列与全局队列
- 【391】栈与队列,Python实现
- java中堆栈内存分析(二)让你彻底明白JAVA中堆与栈的区别(详细)
- RabbitMQ与.net core(三) fanout类型Exchange 与 消息的过期时间 与 队列的存活时间
- [转]Redis作为消息队列与RabbitMQ的性能对比