堆经常用来做优先队列( priority queue)。
以下是简单的java版本。
主要包括插入,添加item, 删除。
public class PriorityQueue<E extends Comparable<E>> {
public static void main(String[] args) {
Integer[] array = { 1, 2, 3, 4, 5 };
PriorityQueue<Integer> heap = new PriorityQueue<Integer>(array);
heap.print();
heap.buildHeap();
heap.print();
heap.delete();
heap.print();
heap.increaseKey(heap.size - 1, 5);
heap.print();
heap.insert(6);
heap.print();
heap.insert(7);
heap.print();
}
private E[] heap;
private int size;
private static final int CAPACITY = 10;
public PriorityQueue() {
heap = (E[]) new Comparable[CAPACITY];
size = 0;
}
public PriorityQueue(E[] array) {
heap = Arrays.copyOf(array, array.length);
size = heap.length;
}
public void print() {
System.out.print("[");
for (int i = 0; i < size; i++) {
System.out.print(heap[i] + " ");
}
System.out.println("]");
}
public void increaseKey(int i, E val) {
if (!checkValid(i))
throw new IndexOutOfBoundsException();
if (heap[i].compareTo(val) > 0) {
throw new IllegalArgumentException("need a higher priority");
}
heap[i] = val;
while (i > 0 & heap[parent(i)].compareTo(val) < 0) {
swap(i, parent(i));
i = parent(i);
}
}
private void maxHeap(int idx) {
int r = right(idx);
int l = left(idx);
int mx = idx;
if (r < size && heap[r].compareTo(heap[mx]) > 0)
mx = r;
if (l < size && heap[l].compareTo(heap[mx]) > 0)
mx = l;
if (mx != idx) {
swap(mx, idx);
maxHeap(mx);
}
}
public void buildHeap() {
int half = size / 2;
for (int i = half; i >= 0; i--) {
maxHeap(i);
}
}
private void swap(int i, int j) {
E tmp = heap[i];
heap[i] = heap[j];
heap[j] = tmp;
}
public int right(int i) {
return 2 * (i + 1);
}
public int left(int i) {
return 2 * i + 1;
}
public int parent(int i) {
return (i - 1) / 2;
}
/**
* check the validation a index
* */
public boolean checkValid(int i) {
if (i >= size)
return false;
else
return true;
}
public E delete() {
if (0 == size)
throw new RuntimeException();
E rvl = heap[0];
size--;
heap[0] = heap[size];
maxHeap(0);
return rvl;
}
public void insert(E val) {
if(heap.length > size){
heap[size] = val;
size++;
}else{
E[] tmp = heap;
heap = (E[])new Comparable[size + CAPACITY];
System.arraycopy(tmp, 0, heap, 0, size);
heap[size] = val;
size++;
}
//need to check
int p = size - 1;
while(p > 0 && heap[parent(p)].compareTo(heap[p]) < 0){
swap(p, parent(p));
p = parent(p);
}
heap[p] = val;
}
}