概述算法
PriorityQueue 意爲優先隊列,表示隊列中的元素是有優先級的,也就是說元素之間是可比較的。所以,插入隊列的元素要實現 Comparable 接口或者 Comparator 接口。api
PriorityQueue 的繼承結構以下:數組
PriorityQueue 沒有實現 BlockingQueue 接口,並不是阻塞隊列。它在邏輯上使用「堆」(即徹底二叉樹)結構實現,物理上基於「動態數組」存儲。如圖所示:數據結構
有關堆的概念可參考前文「數據結構與算法筆記(三)」的相關描述。下面分析其代碼實現。app
代碼分析
dom
成員變量
oop
// 數組的默認初始容量
private static final int DEFAULT_INITIAL_CAPACITY = 11;
// 內部數組,用於存儲隊列中的元素
transient Object[] queue; // non-private to simplify nested class access
// 隊列中元素的個數
private int size = 0;
// 隊列中元素的比較器
private final Comparator<? super E> comparator;
// 結構性修改次數
transient int modCount = 0; // non-private to simplify nested class access
flex
構造器ui
// 構造器 1:無參構造器(默認初試容量爲 11)
public PriorityQueue() {
this(DEFAULT_INITIAL_CAPACITY, null);
}
// 構造器 2:指定容量的構造器
public PriorityQueue(int initialCapacity) {
this(initialCapacity, null);
}
// 構造器 3:指定比較器的構造器
public PriorityQueue(Comparator<? super E> comparator) {
this(DEFAULT_INITIAL_CAPACITY, comparator);
}
// 構造器 4:指定初始容量和比較器的構造器
public PriorityQueue(int initialCapacity,
Comparator<? super E> comparator) {
// Note: This restriction of at least>// but continues for 1.5 compatibility
if (initialCapacity < 1)
throw new IllegalArgumentException();
// 初始化內部數組和比較器
this.queue = new Object[initialCapacity];
this.comparator = comparator;
}
this
這幾個構造器的做用就是初始化內部數組和比較器。
此外,還有幾個稍複雜點的構造器,代碼以下:
// 構造器 5:用給定集合初始化 PriorityQueue 對象
public PriorityQueue(Collection<? extends E> c) {
// 若是集合是 SortedSet 類型
if (c instanceof SortedSet<?>) {
SortedSet<? extends E> ss = (SortedSet<? extends E>) c;
this.comparator = (Comparator<? super E>) ss.comparator();
initElementsFromCollection(ss);
}
// 若是集合是 PriorityQueue 類型
else if (c instanceof PriorityQueue<?>) {
PriorityQueue<? extends E> pq = (PriorityQueue<? extends E>) c;
this.comparator = (Comparator<? super E>) pq.comparator();
initFromPriorityQueue(pq);
}
else {
this.comparator = null;
initFromCollection(c);
}
}
initElementsFromCollection:
// 使用給定集合的元素初始化 PriorityQueue
private void initElementsFromCollection(Collection<? extends E> c) {
// 把集合轉爲數組
Object[] a = c.toArray();
// If c.toArray incorrectly doesn't return Object[], copy it.
if (a.getClass() != Object[].class)
a = Arrays.copyOf(a, a.length, Object[].class);
int len = a.length;
// 確保集合中每一個元素不能爲空
if (len == 1 || this.comparator != null)
for (int i = 0; i < len; i++)
if (a[i] == null)
throw new NullPointerException();
// 初始化 queue 數組和 size
this.queue = a;
this.size = a.length;
}
initFromPriorityQueue:
private void initFromPriorityQueue(PriorityQueue<? extends E> c) {
if (c.getClass() == PriorityQueue.class) {
// 若給定的是 PriorityQueue,則直接進行初始化
this.queue = c.toArray();
this.size = c.size();
} else {
initFromCollection(c);
}
}
initFromCollection:
private void initFromCollection(Collection<? extends E> c) {
// 將集合中的元素轉爲數組,並賦值給 queue(上面已分析)
initElementsFromCollection(c);
// 堆化
heapify();
}
heapify: 堆化,即將數組元素轉爲堆的存儲結構
private void heapify() {
// 從數組的中間位置開始遍歷便可
for (int i = (size >>> 1) - 1; i >= 0; i--)
siftDown(i, (E) queue[i]);
}
PS: 這裏遍歷時,從數組的中間位置遍歷(根據堆的存儲結構,若是某個節點的索引爲 i,則其左右子節點的索引分別爲 2 * i + 1, 2 * i + 2)。
siftDown: 向下篩選?暫未找到恰當的譯法,但這不是重點,該方法的做用就是使數組知足堆結構(其思想與冒泡排序有些相似)。以下:
private void siftDown(int k, E x) {
// 根據 comparator 是否爲空採用不一樣的方法
if (comparator != null)
siftDownUsingComparator(k, x);
else
siftDownComparable(k, x);
}
siftDownUsingComparator:
private void siftDownUsingComparator(int k, E x) {
// 數組的中間位置
int half = size >>> 1;
while (k < half) {
// 獲取索引爲 k 的節點的左子節點索引
int child = (k << 1) + 1;
// 獲取 child 的值
Object c = queue[child];
// 獲取索引爲 k 的節點的右子節點索引
int right = child + 1;
// 左子節點的值大於右子節點,則兩者換位置
if (right < size &&
comparator.compare((E) c, (E) queue[right]) > 0)
// 取左右子節點中較小的一個
c = queue[child = right];
// 給定的元素 x 與較小的子節點的值比較
if (comparator.compare(x, (E) c) <= 0)
break;
// 將該節點與子節點互換
queue[k] = c;
k = child;
}
queue[k] = x;
}
該方法的步驟大概:
1. 找出給定節點(父節點)的子節點中較小的一個,並於之比較大小;
2. 若父節點較大,則交換位置(父節點「下沉」)。
PS: 可參考上面的結構示意圖,其中數組表示隊列中現有的元素,二叉樹表示相應的堆結構,角標表示數組中的索引(有興趣能夠在 IDE 斷點調試驗證)。
siftDownComparable 方法代碼以下:
private void siftDownComparable(int k, E x) {
Comparable<? super E> key = (Comparable<? super E>)x;
int half = size >>> 1; // loop while a non-leaf
while (k < half) {
int child = (k << 1) + 1; // assume left child is least
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;
}
此方法與 siftDownUsingComparator 方法實現邏輯徹底同樣,不一樣的的地方僅在於該方法是針對 Comparable 接口,然後者針對 Comparator 接口,再也不贅述。
此外 PriorityQueue 還有兩個構造器,但都是經過上面的方法實現的,以下:
// 構造器 6:用給定的 PriorityQueue 初始化一個 PriorityQueue
public PriorityQueue(PriorityQueue<? extends E> c) {
this.comparator = (Comparator<? super E>) c.comparator();
initFromPriorityQueue(c);
}
// 構造器 7:用給定的 SortedSet 初始化 PriorityQueue
public PriorityQueue(SortedSet<? extends E> c) {
this.comparator = (Comparator<? super E>) c.comparator();
initElementsFromCollection(c);
}
也再也不贅述。
入隊操做:add(E), offer(E)
兩個入隊操做方法以下:
// 實際是調用 offer 方法實現的
public boolean add(E e) {
return offer(e);
}
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 static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
private void grow(int minCapacity) {
// 原先容量
int oldCapacity = queue.length;
// Double size if small; else grow by 50%
// 原容量較小時,擴大爲原先的兩倍;不然擴大爲原先的 1.5 倍
int newCapacity = oldCapacity + ((oldCapacity < 64) ?
(oldCapacity + 2) :
(oldCapacity >> 1));
// overflow-conscious code
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// 建立一個新的數組
queue = Arrays.copyOf(queue, newCapacity);
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
PS: 擴容操做與前文分析的 ArrayList 和 Vector 的擴容操做相似。
siftUp: 可與 siftDown 方法對比分析
private void siftUp(int k, E x) {
if (comparator != null)
siftUpUsingComparator(k, x);
else
siftUpComparable(k, x);
}
siftUpUsingComparator():
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;
}
該操做也稍微有點繞,仍是以上圖爲基礎繼續操做,示意圖以下:
其中分爲左右兩種狀況:
1. 左邊插入元素爲 7,大於父節點 4,無需和父節點交換位置,直接插入便可;
2. 右邊插入元素爲 1,小於父節點 4,須要和父節點交換位置,並一直往上查找和交換,上圖爲調整後的數組及對應的樹結構。
siftUpComparable:
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;
}
該方法邏輯與 siftUpUsingComparator 同樣,也是 Comparator 和 Comparable 接口的差異。
這裏簡單比較下 siftDown 和 siftUp 這兩個方法:
1. siftDown 是把指定節點與其子節點中較小的一個比較,父節點較大時「下沉(down)」;
2. siftUp 是把指定節點與其父節點比較,若小於父節點,則「上浮(up)」。
出隊操做:poll()
public E poll() {
// 隊列爲空時,返回 null
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;
}
操做的示意圖以下:
該操做的步驟大概以下:
1. 移除隊列的最後一個元素,並將該元素置於首位;
2. 將新的「首位」元素與子節點中較小的一個比較,比較並交換位置(即執行「下沉(siftDown)」操做)。
刪除操做:remove(Object)
public boolean remove(Object o) {
int i = indexOf(o);
if (i == -1)
return false;
else {
removeAt(i);
return true;
}
}
indexOf(o):
// 遍歷數組查找指定元素
private int indexOf(Object o) {
if (o != null) {
for (int i = 0; i < size; i++)
if (o.equals(queue[i]))
return i;
}
return -1;
}
removeAt(i):
private E removeAt(int i) {
// assert i >= 0 && i < size;
modCount++;
int s = --size;
// 移除末尾元素,直接置空
if (s == i) // removed last element
queue[i] = null;
else {
// 末尾元素
E moved = (E) queue[s];
queue[s] = null; // 刪除末尾元素
// 操做與 poll 方法相似
siftDown(i, moved);
// 這裏表示該節點未進行「下沉」調整,則執行「上浮「操做
if (queue[i] == moved) {
siftUp(i, moved);
if (queue[i] != moved)
return moved;
}
}
return null;
}
大概執行步驟:
1. 若移除末尾元素,直接刪除;
2. 若非末尾元素,則將末尾元素刪除,並用末尾元素替換待刪除的元素;
3. 堆化操做:先執行「下沉(siftDown)」操做,若該元素未「下沉」,則再執行「上浮(siftUp)」操做,使得數組刪除元素後仍知足堆結構。
示例代碼
示例一:
private static void test1() {
// 不指定比較器(默認從小到大排序)
Queue<Integer> queue = new PriorityQueue<>();
for (int i = 0; i < 10; i++) {
queue.add(random.nextInt(100));
}
while (!queue.isEmpty()) {
System.out.print(queue.poll() + ". ");
}
}
/* 輸出結果(僅供參考):
* 2, 13, 14, 36, 39, 40, 43, 55, 83, 88,
*/
示例二:指定比較器(Comparator)
private static void test2() {
// 指定比較器(從大到小排序)
Queue<Integer> queue = new PriorityQueue<>(11, (o1, o2) -> o2 - o1);
for (int i = 0; i < 10; i++) {
queue.add(random.nextInt(100));
}
while (!queue.isEmpty()) {
System.out.print(queue.poll() + ", ");
}
}
/* 輸出結果(僅供參考):
* 76, 74, 71, 69, 52, 49, 41, 41, 35, 1,
*/
示例三:求 Top N
public class FixedPriorityQueue {
private PriorityQueue<Integer> queue;
private int maxSize;
public FixedPriorityQueue(int maxSize) {
this.maxSize = maxSize;
// 初始化優先隊列及比較器
// 這裏是從大到小(可調整)
this.queue = new PriorityQueue<>(maxSize, (o2, o1) -> o2.compareTo(o1));
}
public void add(Integer i) {
// 隊列未滿時,直接插入
if (queue.size() < maxSize) {
queue.add(i);
} else {
// 隊列已滿,將待插入元素與最小值比較
Integer peek = queue.peek();
if (i.compareTo(peek) > 0) {
// 大於最小值,將最小值移除,該元素插入
queue.poll();
queue.add(i);
}
}
}
public static void main(String[] args) {
FixedPriorityQueue fixedQueue = new FixedPriorityQueue(10);
for (int i = 1; i <= 100; i++) {
fixedQueue.add(i);
}
Iterable<Integer> iterable = () -> fixedQueue.queue.iterator();
System.out.println("隊列中的元素:");
for (Integer integer : iterable) {
System.out.print(integer + ", ");
}
System.out.println();
System.out.println("最大的 10 個:");
while (!fixedQueue.queue.isEmpty()) {
System.out.print(fixedQueue.queue.poll() + ", ");
}
}
}
/* 輸出結果:
* 隊列中的元素:
* 91, 92, 94, 93, 96, 95, 99, 97, 98, 100,
* 最大的 10 個:
* 91, 92, 93, 94, 95, 96, 97, 98, 99, 100,
*/
小結
1. PriorityQueue 爲優先隊列,實現了 Queue 接口,但並不是阻塞對列;
2. 內部的元素是可比較的(Comparable 或 Comparator),元素不能爲空;
3. 邏輯上使用「堆」(即徹底二叉樹)結構實現,物理上基於「動態數組」存儲;
4. PriorityQueue 可用做求解 Top N 問題。
參考連接:
https://blog.csdn.net/qq_35326718/article/details/72866180
https://my.oschina.net/leejun2005/blog/135085
Stay hungry, stay foolish.