Java中的優先級隊列(一)

優先級隊列的介紹

優先隊列是計算機科學中的一類抽象數據類型。優先隊列中的每一個元素都有各自的優先級,優先級最高的元素最早獲得服務;優先級相同的元素按照其在優先隊列中的順序獲得服務。數組

最小堆性質:除了根之外的全部節點i都有A[PARENT(i)] <= A[i]。PARENT(i)爲i節點的父節點索引。安全

Java中的PriorityQueue

PriorityQueue是從JDK1.5開始提供的新的數據結構接口,一個基於最小堆(徹底二叉樹、堆排序)的無界優先級隊列。特性以下:數據結構

  1. PriorityQueue中的元素可經過元素的天然排序或者經過隊列的構造函數提供一個Comparator對象來排序,若是爲天然排序,則入隊的元素必須實現Comparable接口,不然會拋出ClassCastException異常。
  2. PriorityQueue是不容許null對象入隊的。
  3. PriorityQueue中的頭部元素老是指定排序的最小的元素,若是有多個,則是其中一個。
  4. PriorityQueue內部是由一個自動增加的數組來存儲元素的,默認初始長度是11。
  5. PriorityQueue中的iterator方法不保證以任何特定的順序遍歷隊列中的元素,若是須要排序後再遍歷,則可使用Arrays.sort(pq.toArray())。
  6. PriorityQueue不是線程安全的,若是要線程安全的使用優先級隊列則可使用PriorityBlockingQueue。

PriorityQueue的結構

輸入圖片說明

PriorityQueue內部成員數組queue實際上是實現了一個徹底二叉樹的數據結構,這棵二叉樹的根節點是queue[0],左子節點是queue[1],右子節點是queue[2],而queue[3]又是queue[1]的左子節點,依此類推,給定元素queue[i],該節點的父節點是queue[(i-1)/2]。所以parent變量就是對應於下標爲k的節點的父節點。函數

入隊--O(log(n))

public boolean offer(E e) {
        if (e == null)
            throw new NullPointerException();
        modCount++;
        int i = size;
        if (i >= queue.length)
            grow(i + 1);//數組自動增加
        size = i + 1;
        if (i == 0)
            queue[0] = e;
        else
            siftUp(i, e);
        return true;
    }

 private void siftUp(int k, E x) {
        if (comparator != null)
            siftUpUsingComparator(k, x);
        else
            siftUpComparable(k, x);
    }

private void siftUpComparable(int k, E x) {
        Comparable<? super E> key = (Comparable<? super E>) x;
        while (k > 0) {//自底向上遍歷
            int parent = (k - 1) >>> 1;//定位父節點
            Object e = queue[parent];
            if (key.compareTo((E) e) >= 0)//大於等於父節點便中止遍歷
                break;
            queue[k] = e;//若是小於則交換
            k = parent;
        }
        queue[k] = key;
    }

private void siftUpUsingComparator(int k, E x) {
        while (k > 0) {
            int parent = (k - 1) >>> 1;
            Object e = queue[parent];
            if (comparator.compare(x, (E) e) >= 0)
                break;
            queue[k] = e;
            k = parent;
        }
        queue[k] = x;
    }

從源代碼角度看,整個入隊過程主要作兩件事:第一是判別queue數組是否須要擴容;第二是從葉子節點到根節點的排序。線程

出隊--O(log(n))

public E poll() {
        if (size == 0)
            return null;
        int s = --size;
        modCount++;
        E result = (E) queue[0];
        E x = (E) queue[s];
        queue[s] = null;
        if (s != 0)
            siftDown(0, x);
        return result;
    }

private void siftDown(int k, E x) {
        if (comparator != null)
            siftDownUsingComparator(k, x);
        else
            siftDownComparable(k, x);
    }

private void siftDownComparable(int k, E x) {
        Comparable<? super E> key = (Comparable<? super E>)x;
        int half = size >>> 1;        // 循環至非葉子節點便可,徹底二叉樹性質:小於size/2的節點必有孩子節點,大於size/2的節點必是葉子節點
        while (k < half) {
            int child = (k << 1) + 1; // 左孩子節點索引
            Object c = queue[child];// 左孩子元素
            int right = child + 1;// 右孩子節點索引
            if (right < size &&
                ((Comparable<? super E>) c).compareTo((E) queue[right]) > 0) //右孩子存在且右孩子小於等於左孩子
                c = queue[child = right]; //選擇孩子節點中較小的元素
            if (key.compareTo((E) c) <= 0)// 若是小於等於則中止
                break;
            queue[k] = c;// 大於則交換而且繼續
            k = child;
        }
        queue[k] = key;
    }

private void siftDownUsingComparator(int k, E x) {
        int half = size >>> 1;
        while (k < half) {
            int child = (k << 1) + 1;
            Object c = queue[child];
            int right = child + 1;
            if (right < size &&
                comparator.compare((E) c, (E) queue[right]) > 0)
                c = queue[child = right];
            if (comparator.compare(x, (E) c) <= 0)
                break;
            queue[k] = c;
            k = child;
        }
        queue[k] = x;
    }

從源代碼角度看,整個出隊過程主要作三件事:第一是使用局部變量result保存隊頭重的元素,以便返回;第二是使用局部變量x保存隊尾元素;第三是將隊尾元素看做是插入到隊頭處,而後是從根節點到葉子節點的排序code

相關文章
相關標籤/搜索