java 优先队列

队列的基本准则就是先进先出,优先队列有两种,一种就是最大优先队列,就是不管入队元素,先让队列里的最大值先出队,另一种就是最小优先队列,就是不管入队元素,先让队列里的最小的元素先出队,运用二叉堆的方法可以实现它,把队列里的元素调整成大顶堆或者小顶堆,最后获取堆顶的元素进行了。

package shujujiegou;

import java.util.Arrays;

/**
 * 优先级队列
 * @author TomCat
 *
 */
public class PropertityQueue {
	private int[] array;
	private int size;
	public PropertityQueue() {
		//队列的初始长度为32
		array=new int[32];
	}
	/**
	 * 入队
	 */
	private void enQueue(int key) {
		if(size>=array.length) {
			resize();
		}
		array[size++]=key;
		upAdjust();
	}
	
	/**
	 * 出队
	 * @throws Exception 
	 */
	private int deQueue() throws Exception {
		if(size<=0) {
			throw  new Exception("队列为空");
		}
		//获取堆顶的元素
		int head=array[0];
		//最后一个元素移动到堆顶
		array[0]=array[--size];
		downAdjust();
		return head;
	}
	private void downAdjust() {
		// TODO Auto-generated method stub
		int parentIndex=0;
		int temp=array[parentIndex];
		int childIndex=1;
		while(childIndex<size) {
			if(childIndex+1<size&&array[childIndex+1]>array[childIndex]) {
				childIndex++;
			}
			if(temp>=array[childIndex]) {
				break;
			}
			array[parentIndex]=array[childIndex];
			parentIndex=childIndex;
			childIndex=2*childIndex+1;
		}
		array[parentIndex]=temp;
		
	}
	public void resize() {
		int newSize=this.size*2;
		this.array=Arrays.copyOf(this.array, newSize);
	}
	private void upAdjust() {
		// TODO Auto-generated method stub
		int childIndex=size-1;
		int parentIndex=childIndex/2;
		//temp用于保存插入叶子节点的值,用于最后的赋值操作
		int temp=array[childIndex];
		while(childIndex>0&&temp>array[parentIndex]) {
			array[childIndex]=array[parentIndex];
			childIndex=parentIndex;
			parentIndex=parentIndex/2;
		}
		array[childIndex]=temp;
		
	}
	public static void main(String[] args) throws Exception {
		PropertityQueue  p=new PropertityQueue();
		p.enQueue(1);
		p.enQueue(5);
		p.enQueue(2);
		p.enQueue(3);
		p.enQueue(10);
		System.out.println("出队元素"+p.deQueue());
		System.out.println("出队元素"+p.deQueue());
	}
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值