class MinHeap {
constructor() {
this.heap = []
this.buildHeapArr = []
}
getParentIndex(i) {
return Math.floor((i - 1)/2)
}
// 获取左节点
getLeftIndex(i) {
return i * 2 + 1;
}
// 获取右节点
getRightIndex(i) {
return i * 2 + 2;
}
// 交换值
swap(i1, i2,arr) {
const temp = arr[i1];
arr[i1] = arr[i2];
arr[i2] = temp;
}
shiftUp(index,arr) {
//到达堆顶就不用上移了
if (index == 0) { return; }
const parentIndex = this.getParentIndex(index);
// 最小堆要求父节点是最小的
if (arr[parentIndex] > arr[index]) {
this.swap(parentIndex, index,arr);
// 交换过后尝试继续上移
this.shiftUp(parentIndex,arr);
}
}
shiftDown(index,arr) {
const leftIndex = this.getLeftIndex(index);
const rightIndex = this.getRightIndex(index);
if (arr[leftIndex] < arr[index]) {
this.swap(leftIndex, index,arr);
this.shiftDown(leftIndex,arr);
}
if (arr[rightIndex] < arr[index]) {
this.swap(rightIndex, index,arr);
this.shiftDown(rightIndex,arr);
}
}
insert(value,arr) {
arr.push(value);
this.shiftUp(arr.length - 1,arr);
}
pop(arr) {
arr[0] = arr.pop();
this.shiftDown(0,arr);
}
// 构建堆结构
buildHeap(arr) {
let temp = []
for(let i = 0;i<arr.length;i++) {
this.insert(arr[i],temp)
}
return temp
}
// 堆排序
sort(arr) {
let temp = []
let heapArr = this.buildHeap(arr)
while(heapArr.length) {
temp.push(heapArr.shift())
heapArr = this.buildHeap(heapArr)
}
return temp
}
}
数据结构堆js
于 2022-08-11 16:24:49 首次发布