主要是支持对优先队列中某元素属性值的修改(通过equals查找, 并替换新的引用), 可以用于A*算法框架...
import java.util.*;
@SuppressWarnings("unchecked")
public class Heap<E extends Comparable<E>>{
private E[] heap; // E[0] is not used...
private int num;
private Comparator<E> cmp;
public Heap() {
heap = (E[]) new Comparable[16];
}
public Heap(int n) {
heap = (E[]) new Comparable[n];
}
public Heap(Comparator<E> cmp) {
this();
this.cmp = cmp;
}
public Heap(int n, Comparator<E> cmp) {
this(n);
this.cmp = cmp;
}
private int compare(E e1, E e2) {
return (cmp == null) ? e1.compareTo(e2) : cmp.compare(e1, e2);
}
public void add(E e) {
if (num == heap.length - 1) {
E[] newHeap = (E[]) new Comparable[2 * heap.length];
System.arraycopy(heap, 0, newHeap, 0, heap.length);
heap = newHeap;
}
heap[++num] = e;
raise(num);
}
public E peek() {
if (num == 0)
throw new NoSuchElementException();
return heap[1];
}
public E poll() {
if (num == 0)
throw new NoSuchElementException();
E e = heap[1];
heap[1] = heap[num--];
sink(1);
return e;
}
private void raise(int hole) {
E e = heap[hole];
for ( ; hole > 1 && compare(e, heap[hole/2]) < 0; hole /= 2)
heap[hole] = heap[hole/2];
heap[hole] = e;
}
private void sink(int hole) {
int child;
E e = heap[hole];
for ( ; hole * 2 < num; hole = child) {
child = hole * 2;
if (child < num && compare(heap[child+1], heap[child]) < 0)
child++;
if (compare(heap[child], e) < 0)
heap[hole] = heap[child];
else
break;
}
heap[hole] = e;
}
public int indexOf(E e) {
for (int i = 1; i <= num; i++)
if (heap[i].equals(e))
return i;
return -1;
}
public void changeTo(E e1, E e2) {
int i = indexOf(e1);
if (i == -1)
return;
heap[i] = e2;
if (compare(e2, e1) < 0)
raise(i);
else if (compare(e2, e1) > 0)
sink(i);
}
public boolean isEmpty() {
return num == 0;
}
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= num; i++)
sb.append(heap[i] + " ");
return sb.toString();
}
public static void main(String[] args) {
Heap<Integer> heap = new Heap<Integer>();
int[] nums = new int[10];
Random r = new Random();
for (int i = 0; i < nums.length; i++) {
nums[i] = r.nextInt(100);
heap.add(nums[i]);
}
System.out.println("----- Original -----");
System.out.println(Arrays.toString(nums));
System.out.println("-- Priority Queue --");
System.out.println(heap);
int x = nums[r.nextInt(nums.length)];
int y = 33;
heap.changeTo(x, y);
System.out.format("change %d to %d in heap.\n", x, y);
System.out.println(heap);
}
}