优先序列

33 篇文章 0 订阅

堆经常用来做优先队列( 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;
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值