算法__优先队列

最大优先队列:无论入队顺序,最大的数字先出队;

最小优先队列:无论入队顺序,最小的数字先出队;

7 5 4 2 3 1  

二叉树:

 插入一个数字 8:

  8  大于 4,4和8交换;  8 大于7 ,8和7交换。

代码如下:

/**
 * 优先排序(最大优先队列)
 */
public class TestPro {

    //队列的大小
    private int size = 32;
    private int[] arrays;
    //下一个需要存储的座标
    private int position = 0;

    public TestPro() {
        arrays = new int[size];
    }

    public TestPro(int size) {
        arrays = new int[size];
    }

    /**
     * 添加数据
     *
     * @param number 数值
     */
    public void enQueue(int number) {
        if (position >= size)
            reSize();
        arrays[position++] = number;
        upJust();
    }

    /**
     * 输出最大的值
     *
     * @return 最大值
     * @throws Exception 没有值了
     */
    public int outQueue() throws Exception {
        if (position <= 0)
            throw new Exception("没有值可出了。。。");

        int head = arrays[0];
        arrays[0] = arrays[--position];
        downJust();
        return head;
    }

    /**
     * 扩张一倍数组
     */
    private void reSize() {
        size = size * 2;
        arrays = Arrays.copyOf(arrays, size);
    }

    /**
     * 上浮调整
     */
    private void upJust() {
        int childIndex = position - 1;
        int lastNumber = arrays[childIndex];
        int parentIndex = (childIndex - 1) / 2;
        while (childIndex > 0 && lastNumber > arrays[parentIndex]) {
            arrays[childIndex] = arrays[parentIndex];
            childIndex = parentIndex;
            parentIndex = (childIndex - 1) / 2;
        }
        arrays[childIndex] = lastNumber;
    }

    /**
     * 下沉调整
     */
    private void downJust() {
        int childIndex = 1, parentIndex = 0;
        int parentNumber = arrays[0];
        while (childIndex < position) {
            if (childIndex + 1 < position && arrays[childIndex + 1] > arrays[childIndex]) {
                childIndex++;
            }

            if (parentNumber > arrays[childIndex])
                break;

            arrays[parentIndex] = arrays[childIndex];
            parentIndex = childIndex;
            childIndex = parentIndex * 2 + 1;
        }
        arrays[parentIndex] = parentNumber;
    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章