【底层代码欣赏】—— PriorityQueue中的poll方法

 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;
 9         if (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

posted @ 2021-11-08 13:43  吾辈当奋斗-生生不息  阅读(185)  评论(0)    收藏  举报