【底層程式碼欣賞】—— PriorityQueue中的poll方法
阿新 • • 發佈:2021-11-08
1 public E poll() { 2 if (size == 0) 3 return null; 4 int s = --size; 5 modCount++; 6 E result = (E) queue[0];//0下標處的那個元素就是最小的那個 7 E x = (E) queue[s]; 8 queue[s] = null; 9 if (s != 0) 10 siftDown(0, x);//調整 11 return result; 12 }
向下調整,每次和孩子節點中較小的那一個交換
1//siftDown() 2 private void siftDown(int k, E x) { 3 int half = size >>> 1; 4 while (k < half) { 5 //首先找到左右孩子中較小的那個,記錄到c裡,並用child記錄其下標 6 int child = (k << 1) + 1;//leftNo = parentNo*2+1 7 Object c = queue[child]; 8 int right = child + 1; 9if (right < size && 10 comparator.compare((E) c, (E) queue[right]) > 0) 11 c = queue[child = right]; 12 if (comparator.compare(x, (E) c) <= 0) 13 break; 14 queue[k] = c;//然後用c取代原來的值 15 k = child; 16 } 17 queue[k] = x;18 }
圖解:
參考:https://pdai.tech/md/java/collection/java-collection-PriorityQueue.html