算法__優先隊列

最大優先隊列:無論入隊順序,最大的數字先出隊;

最小優先隊列:無論入隊順序,最小的數字先出隊;

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;
    }

}

 

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