一个简单的堆...

主要是支持对优先队列中某元素属性值的修改(通过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);
	}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值