優先隊列實現原理分析

DixieBatson 7年前發布 | 35K 次閱讀 優先隊列 算法

優先隊列是在實際工程中被廣泛應用的一種數據結構,不管是在操作系統的進程調度中,還是在相關的圖算法比如Prim算法和Dijkstra算法中,我們都可以看到優先隊列的身影,本文我們就來分析一下優先隊列的實現原理。

優先隊列

以操作系統的進程調度為例,比如我們在使用手機的過程中,手機分配給來電的優先級都會比其它程序高,在這個業務場景中,我們不要求所有元素全部有序,因為我們需要處理的只是當前鍵值最大的元素(優先級最高)。在這種情況下,我們需要實現的只是刪除最大的元素和插入新的元素,這種數據結構就叫做優先隊列。

在正式實現優先隊列之前,我們有必要先來了解一下對于堆的相關操作。

堆的基本概念

我們定義當一棵二叉樹的每個結點都要大于等于它的兩個子結點的時候,稱這棵二叉樹堆有序。如下圖就是一棵典型的堆有序的完全二叉樹。

堆上浮和下沉操作

對了保證堆有序,對于堆我們要對它進行上浮和下沉操作,我們先來實現兩個常用的工具方法,其中 less() 用于比較兩個元素的大小, exch() 用于交換數組的兩個元素:

private static boolean less(Comparable[] pq, int i, int j){
 return pq[i-1].compareTo(pq[j-1]) < 0;
}

private static void exch(Object[] pq, int i, int j){
 Object swap = pq[i-1];
 pq[i-1] = pq[j-1];
 pq[j-1] = swap;
}

上浮操作

根據下圖我們首先來分析一下上浮操作,以 swim(5) 為例子,我們來看一下上浮的過程。對于堆我們進行上浮的目的是保持堆有序性,即一個結點的值大于它的子結點的值,所以我們將 a[5] 和它的父結點 a[2] 相比較,如果它大于父結點的值,我們就交換兩者,然后繼續 swim(2) 。

具體的實現代碼的非常簡單如下:

private void swim(Comparable[] pq, int k){
 while (k > 1 && less(k/2, k) {
 exch(k/2, k);
 k = k/2;
 }
}

下沉操作

根據下圖我們來分析一下下沉操作,我們將結點 a[2] 和它兩個子結點中較小的結點相比較,如果小于子結點,我們就交換兩者,然后繼續 sink(5) 。

private static void sink(Comparable[] pq, int k, int n){
 while (2*k <= n) {
 int j = 2*k;
 if (j < n && less(pq, j, j+1)) j++;
 if (!less(pq, k, j)) break;
 exch(pq, k, j);
 k = j;
 }
}

實現

在實現優先隊列前,我們先來定義一個優先隊列,下面我們將使用 pq[] 來保存相關的元素,在構造函數中可以指定堆的初始化大小,如果不指定初始化大小,默認初始化值為1。p.s: 在下面我們會實現相關的 resize() 方法用來動態調整數組的大小。

public class MaxPQ<Key> implements Iterable<Key>{
 private Key[] pq; // store items at indices 1 to n
 private int n; // number of items on priority queue
 private Comparator<Key> comparator; // optional Comparator

 /**
 * Initializes an empty priority queue with the given initial capacity.
 *
 * @param initCapacity the initial capacity of this priority queue
 */
 public MaxPQ(int initCapacity){
 pq = (Key[]) new Object[initCapacity + 1];
 n = 0;
 }

 /**
 * Initializes an empty priority queue.
 */
 public MaxPQ(){
 this(1);
 }

我們首先來分析一下插入元素的過程,如果我們要在一個堆中新插入一個元素 S 的話,首先我們默認將這個元素插入到數組中 P[N++] 中(數組是從1開始計數的)。當我們插入 S 后,打破了堆的有序性,所以我們采用上浮操作來維持堆的有序性,當上浮操作結束之后,我們依然可以保證根結點的元素是數組中最大的元素。

接下來我們來看一下刪除最大元素的過程,我們首先將最大的元素 a[1] 和 a[N] 交換,然后我們刪除最大元素 a[N] ,這個時候堆的有序性已經被打破了,所以我們繼續通過下沉操作來重新維持堆的有序性,保持根結點元素是所有元素中最大的元素。

插入的實現代碼如下:

/**
 * Associate key with index i.
 *
 * @param i an index
 * @param key the key to associate with index i
 * @throws IndexOutOfBoundsException unless i < maxN
 * @throws IllegalArgumentException if there already is an item
 * associated with index i
 */
public void insert(Key x){
 // double size of array if necessary
 if (n >= pq.length - 1) resize(2 * pq.length);

 // add x, and percolate it up to maintain heap invariant
 pq[++n] = x;
 swim(n);
 assert isMaxHeap();
}

刪除的實現代碼如下:

/**
 * Removes a maximum key and returns its associated index.
 *
 * @return an index associated with a maximum key
 * @throws NoSuchElementException if this priority queue is empty
 */
public Key delMax(){
 if (isEmpty()) throw new NoSuchElementException("Priority queue underflow");
 Key max = pq[1];
 exch(1, n);
 n--;
 sink(1);
 pq[n+1] = null; // to avoid loiterig and help with garbage collection
 if ((n > 0) && (n == (pq.length - 1) / 4)) resize(pq.length / 2);
 assert isMaxHeap();
 return max;
}

上面我們用到在 insert() 過程用到了 resize() 函數,它用于動態數組的大小,具體的實現代碼如下:

// helper function to double the size of the heap array
private void resize(int capacity){
 assert capacity > n;
 Key[] temp = (Key[]) new Object[capacity];
 for (int i = 1; i <= n; i++) {
 temp[i] = pq[i];
 }
 pq = temp;
}

而 isMaxHeap() 則用于判斷當前數組是否滿足堆有序原則,這在debug的時候非常的有用,具體的實現代碼如下:

// is pq[1..N] a max heap?
private boolean isMaxHeap(){
 return isMaxHeap(1);
}

// is subtree of pq[1..n] rooted at k a max heap?
private boolean isMaxHeap(int k){
 if (k > n) return true;
 int left = 2*k;
 int right = 2*k + 1;
 if (left <= n && less(k, left)) return false;
 if (right <= n && less(k, right)) return false;
 return isMaxHeap(left) && isMaxHeap(right);
}

到此我們的優先隊列已經差不多完成了,注意我們上面實現了 Iterable<Key> 接口,所以我們來實現 iterator() 方法。

/**
 * Returns an iterator that iterates over the keys on this priority queue
 * in descending order.
 * The iterator doesn't implement remove() since it's optional.
 *
 * @return an iterator that iterates over the keys in descending order
 */
public Iterator<Key> iterator(){
 return new HeapIterator();
}

private class HeapIterator implements Iterator<Key>{

 // create a new pq
 private MaxPQ<Key> copy;

 // add all items to copy of heap
 // takes linear time since already in heap order so no keys move
 public HeapIterator(){
 if (comparator == null) copy = new MaxPQ<Key>(size());
 else copy = new MaxPQ<Key>(size(), comparator);
 for (int i = 1; i <= n; i++)
 copy.insert(pq[i]);
 }

 public boolean hasNext(){ return !copy.isEmpty(); }
 public void remove(){ throw new UnsupportedOperationException(); }

 public Key next(){
 if (!hasNext()) throw new NoSuchElementException();
 return copy.delMax();
 }
}

堆排序

對于堆排序的具體實現,我們下面分為兩個步驟:

  1. 首先我們先來構造一個堆。
  2. 然后通過下沉的方式進行排序。

堆排序的實現代碼非常的簡短,我們首先來看一下具體的代碼實現,然后我們再具體分析它的實現原理:

/**
 * Rearranges the array in ascending order, using the natural order.
 * @param pq the array to be sorted
 */
public static void sort(Comparable[] pq){
 int n = pq.length;
 for (int k = n/2; k >= 1; k--)
 sink(pq, k, n);
 while (n > 1) {
 exch(pq, 1, n--);
 sink(pq, 1, n);
 }
}

首先我們來看一下堆的構造過程(下圖中的左圖)。我們采用的方法是從右至左用 sink() 方法構造子堆。我們只需要掃描數組中的一半元素,即5, 4, 3, 2, 1。這樣通過這幾個步驟,我們可以得到一個堆有序的數組,即每個結點的大小都大于它的兩個結點,并使最大元素位于數組的開頭。

接下來我們來分析一下下沉排序的實現(下圖中的右圖),這里我們采取的方法是每次都將最大的元素刪除,然后重新通過 sink() 來維持堆有序,這樣每一次 sink() 操作我們都可以的到數組中最大的元素。

 

來自:http://www.ziwenxie.site/2017/03/30/algorithm-priority-queue/

 

 本文由用戶 DixieBatson 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!