优先队列代码实现

import java.util.Arrays;

/**
 * 时间复杂度 logn
 * @author liyhu
 *
 */
public class PriorityQueue {

    private int[] array;
    private int size;
    public PriorityQueue() {
        super();
        array=new int[32];
    }
    /**
     * 
     * @Description: (入队) 
     * @author: liyhui
     * @date: 2018年11月24日
     * @param key
     */
    private void enQueue(int key) {
        //队列长度超出范围,扩容
        if(size >= array.length) {
            resize();
        }
        array[size++]=key;
        upAdjust();
    }
    /**
     * 
     * @Description: (出队) 
     * @author: liyhui
     * @date: 2018年11月24日
     * @return
     */
    private int deQueue() {
        if(size < 0) {
            throw new RuntimeException("the queue is empty");
        }
        //获取堆顶元素
        int head=array[0];
        //最后一个元素移动到堆顶
        array[0]=array[--size];
        downAdjust();
        return head;
    }
    /**
     * 
     * @Description: (下沉) 
     * @author: liyhui
     * @date: 2018年11月24日
     */
    private void downAdjust() {
        int parentIndex=0;
        //temp 保存插入的父节点值,用于最后赋值
        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= childIndex << 1 + 1;
        }
        array[parentIndex]=temp;
    }
    /**
     * 
     * @Description: (上浮) 
     * @author: liyhui
     * @date: 2018年11月24日
     */
    private void upAdjust() {
        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 >> 1;
        }
        array[childIndex]=temp;
    }
    /**
     * 
     * @Description: (扩容) 
     * @author: liyhui
     * @date: 2018年11月24日
     */
    private void resize() {
        // 队列容量翻倍
        int newSize=this.size << 1;
        this.array=Arrays.copyOf(this.array, newSize);        
    }
    public static void main(String[] args) {
        
        PriorityQueue queue=new PriorityQueue();
        queue.enQueue(3);
        queue.enQueue(5);
        queue.enQueue(10);
        queue.enQueue(2);
        queue.enQueue(7);
        System.out.println("出队元素:"+queue.deQueue());
        System.out.println("出队元素:"+queue.deQueue());
    }
    
}

猜你喜欢

转载自www.cnblogs.com/dongma/p/10012661.html