欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

JS手写最小堆(小顶堆)、最大堆(大顶堆)

最编程 2023-12-31 14:45:16
...
let heap = []; function swap(index1, index2) { [heap[index1], heap[index2]] = [heap[index2], heap[index1]] } function shiftup(index) { let parentIndex = Math.floor((index - 1) / 2); if (index != 0 && heap[parentIndex] > heap[index]) { swap(parentIndex, index); shiftup(parentIndex); } } function shiftDown(index) { let leftNodeIndex = (index + 1) * 2 - 1, rightNodeIndex = (index + 1) * 2 if (leftNodeIndex < heap.length && heap[leftNodeIndex] < heap[index]) { swap(leftNodeIndex, index); shiftDown(leftNodeIndex); } if (rightNodeIndex < heap.length && heap[rightNodeIndex] < heap[index]) { swap(rightNodeIndex, index); shiftDown(rightNodeIndex); } } function insert(val) { heap.push(val); shiftup(heap.length - 1); } function remove() { swap(0, heap.length - 1); let temp = heap.pop(); shiftDown(0); return temp; }