@graphty/algorithms
Version:
Graph algorithms library for browser environments implemented in TypeScript
101 lines • 3.06 kB
JavaScript
/**
* Min Priority Queue implementation for graph algorithms
*/
export class MinPriorityQueue {
constructor(compareFunction) {
this.heap = [];
this.compare = compareFunction ?? ((a, b) => this.defaultCompare(a, b));
}
defaultCompare(a, b) {
const aWithDistance = a;
const bWithDistance = b;
if (aWithDistance.distance !== undefined && bWithDistance.distance !== undefined) {
return aWithDistance.distance - bWithDistance.distance;
}
return 0;
}
parent(i) {
return Math.floor((i - 1) / 2);
}
leftChild(i) {
return (2 * i) + 1;
}
rightChild(i) {
return (2 * i) + 2;
}
swap(i, j) {
const temp = this.heap[i];
const temp2 = this.heap[j];
if (temp !== undefined && temp2 !== undefined) {
this.heap[i] = temp2;
this.heap[j] = temp;
}
}
heapifyUp(index) {
while (index > 0) {
const parentIndex = this.parent(index);
const current = this.heap[index];
const parent = this.heap[parentIndex];
if (current !== undefined && parent !== undefined && this.compare(current, parent) < 0) {
this.swap(index, parentIndex);
index = parentIndex;
}
else {
break;
}
}
}
heapifyDown(index) {
while (index < this.heap.length) {
let minIndex = index;
const left = this.leftChild(index);
const right = this.rightChild(index);
const leftItem = this.heap[left];
const minItem = this.heap[minIndex];
if (left < this.heap.length && leftItem !== undefined && minItem !== undefined && this.compare(leftItem, minItem) < 0) {
minIndex = left;
}
const rightItem = this.heap[right];
const newMinItem = this.heap[minIndex];
if (right < this.heap.length && rightItem !== undefined && newMinItem !== undefined && this.compare(rightItem, newMinItem) < 0) {
minIndex = right;
}
if (minIndex !== index) {
this.swap(index, minIndex);
index = minIndex;
}
else {
break;
}
}
}
insert(value) {
this.heap.push(value);
this.heapifyUp(this.heap.length - 1);
}
extractMin() {
if (this.heap.length === 0) {
return undefined;
}
if (this.heap.length === 1) {
return this.heap.pop();
}
const min = this.heap[0];
const last = this.heap.pop();
if (last !== undefined) {
this.heap[0] = last;
this.heapifyDown(0);
}
return min;
}
peek() {
return this.heap[0];
}
isEmpty() {
return this.heap.length === 0;
}
size() {
return this.heap.length;
}
}
//# sourceMappingURL=priorityQueue.js.map