UNPKG

107w-heap

Version:

提供js堆排序(优先级队列)数据结构

58 lines 1.49 kB
// 更高性能(其实不明所以)去掉!就是最大堆 /* 传入回调函数morethen,定义比较方法,> 最小堆, < 最大堆 最小堆 new BigHeap(function (i, j) { return this.heap[i] > this.heap[j]; }) 最大堆 new BigHeap(function (i, j) { return this.heap[i] < this.heap[j]; }) */ class BigHeap { constructor(morethan = function(i, j) {return this.heap[i] > this.heap[j]}) { this.morethan = morethan this.heap = []; this.heap[0] = null; // 占位,不使用 this.count = 0; // 堆元素个数 } insert(n) { this.heap.push(n); this.count++; this.swim(this.heap.length - 1); } swim(i) { while (i > 1 && !this.morethan(i, this.parent(i))) { this.each(i, this.parent(i)); i = this.parent(i); } } sink(i) { while (i < this.heap.length) { let left = 2 * i, right = 2 * i + 1, temp = i, len = this.heap.length; if (left < len && !this.morethan(left, temp)) temp = left; if (right < len && !this.morethan(right, temp)) temp = right; if (temp == i) return; this.each(temp, i); i = temp; } } parent(i) { return i >> 1; } each(i, j) { [this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]]; } delMax() { this.each(1, this.heap.length - 1); this.count--; let max = this.heap.pop(); this.sink(1); return max; } } module.exports = BigHeap