Skip to content

Commit cea50b7

Browse files
gurgundayaduh95
authored andcommitted
lib: optimize priority queue
PR-URL: #57100 Reviewed-By: Daniel Lemire <daniel@lemire.me> Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com> Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de>
1 parent b74e0ff commit cea50b7

1 file changed

Lines changed: 30 additions & 19 deletions

File tree

‎lib/internal/priority_queue.js‎

Lines changed: 30 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -47,20 +47,28 @@ module.exports = class PriorityQueue {
4747
constsetPosition=this.#setPosition;
4848
constheap=this.#heap;
4949
constsize=this.#size;
50+
consthsize=size>>1;
5051
constitem=heap[pos];
5152

52-
while(pos*2<=size){
53-
letchildIndex=pos*2+1;
54-
if(childIndex>size||compare(heap[pos*2],heap[childIndex])<0)
55-
childIndex=pos*2;
56-
constchild=heap[childIndex];
57-
if(compare(item,child)<=0)
58-
break;
53+
while(pos<=hsize){
54+
letchild=pos<<1;
55+
constnextChild=child+1;
56+
letchildItem=heap[child];
57+
58+
if(nextChild<=size&&compare(heap[nextChild],childItem)<0){
59+
child=nextChild;
60+
childItem=heap[nextChild];
61+
}
62+
63+
if(compare(item,childItem)<=0)break;
64+
5965
if(setPosition!==undefined)
60-
setPosition(child,pos);
61-
heap[pos]=child;
62-
pos=childIndex;
66+
setPosition(childItem,pos);
67+
68+
heap[pos]=childItem;
69+
pos=child;
6370
}
71+
6472
heap[pos]=item;
6573
if(setPosition!==undefined)
6674
setPosition(item,pos);
@@ -73,27 +81,30 @@ module.exports = class PriorityQueue {
7381
constitem=heap[pos];
7482

7583
while(pos>1){
76-
constparent=heap[pos/2|0];
77-
if(compare(parent,item)<=0)
84+
constparent=pos>>1;
85+
constparentItem=heap[parent];
86+
if(compare(parentItem,item)<=0)
7887
break;
79-
heap[pos]=parent;
88+
heap[pos]=parentItem;
8089
if(setPosition!==undefined)
81-
setPosition(parent,pos);
82-
pos=pos/2|0;
90+
setPosition(parentItem,pos);
91+
pos=parent;
8392
}
93+
8494
heap[pos]=item;
8595
if(setPosition!==undefined)
8696
setPosition(item,pos);
8797
}
8898

8999
removeAt(pos){
90100
constheap=this.#heap;
91-
constsize=--this.#size;
92-
heap[pos]=heap[size+1];
93-
heap[size+1]=undefined;
101+
letsize=this.#size;
102+
heap[pos]=heap[size];
103+
heap[size]=undefined;
104+
size=--this.#size;
94105

95106
if(size>0&&pos<=size){
96-
if(pos>1&&this.#compare(heap[pos/2|0],heap[pos])>0)
107+
if(pos>1&&this.#compare(heap[pos>>1],heap[pos])>0)
97108
this.percolateUp(pos);
98109
else
99110
this.percolateDown(pos);

0 commit comments

Comments
 (0)