lib: optimize priority queue

PR-URL: https://github.com/nodejs/node/pull/57100
Reviewed-By: Daniel Lemire <daniel@lemire.me>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de>
This commit is contained in:
Gürgün Dayıoğlu authored and RafaelGSS committed 2025-05-02 17:04:38 -03:00
1 parent 9bbf5bdf76
commit ae58de21d9
1 file changed
+30 -19
+30 -19
View File
@@ -47,20 +47,28 @@ module.exports = class PriorityQueue {
const setPosition = this.#setPosition;
const heap = this.#heap;
const size = this.#size;
const hsize = size >> 1;
const item = heap[pos];
while (pos * 2 <= size) {
let childIndex = pos * 2 + 1;
if (childIndex > size || compare(heap[pos * 2], heap[childIndex]) < 0)
childIndex = pos * 2;
const child = heap[childIndex];
if (compare(item, child) <= 0)
break;
while (pos <= hsize) {
let child = pos << 1;
const nextChild = child + 1;
let childItem = heap[child];
if (nextChild <= size && compare(heap[nextChild], childItem) < 0) {
child = nextChild;
childItem = heap[nextChild];
}
if (compare(item, childItem) <= 0) break;
if (setPosition !== undefined)
setPosition(child, pos);
heap[pos] = child;
pos = childIndex;
setPosition(childItem, pos);
heap[pos] = childItem;
pos = child;
}
heap[pos] = item;
if (setPosition !== undefined)
setPosition(item, pos);
@@ -73,14 +81,16 @@ module.exports = class PriorityQueue {
const item = heap[pos];
while (pos > 1) {
const parent = heap[pos / 2 | 0];
if (compare(parent, item) <= 0)
const parent = pos >> 1;
const parentItem = heap[parent];
if (compare(parentItem, item) <= 0)
break;
heap[pos] = parent;
heap[pos] = parentItem;
if (setPosition !== undefined)
setPosition(parent, pos);
pos = pos / 2 | 0;
setPosition(parentItem, pos);
pos = parent;
}
heap[pos] = item;
if (setPosition !== undefined)
setPosition(item, pos);
@@ -88,12 +98,13 @@ module.exports = class PriorityQueue {
removeAt(pos) {
const heap = this.#heap;
const size = --this.#size;
heap[pos] = heap[size + 1];
heap[size + 1] = undefined;
let size = this.#size;
heap[pos] = heap[size];
heap[size] = undefined;
size = --this.#size;
if (size > 0 && pos <= size) {
if (pos > 1 && this.#compare(heap[pos / 2 | 0], heap[pos]) > 0)
if (pos > 1 && this.#compare(heap[pos >> 1], heap[pos]) > 0)
this.percolateUp(pos);
else
this.percolateDown(pos);