let arr = [3, 4, 6, 7, 3, 5, 1, 8, 1, 1, 7, 5, 5, 10, 3, 2, 2];
let heapInsert = (arr, index) => { //建造大根堆
let next = Math.floor((index - 1) / 2);
while (arr[index] > arr[next]) {
[arr[index], arr[next]] = [arr[next], arr[index]];
index = next;
next = Math.floor((index - 1) / 2);
}
};
let heapify = (arr, index, heapSize) => {
let left = index * 2 + 1;
while (left < heapSize) {
let largest = (left + 1 < heapSize && arr[left] < arr[left + 1]) ? left + 1 : left;
largest = (arr[index] > arr[largest]) ? index : largest;
if (largest === index) {
break;
}
[arr[largest], arr[index]] = [arr[index], arr[largest]];
index = largest; //不要忘记这一步
left = 2 * index + 1;
}
};
let heapSort = (arr) => {
if (arr === null || arr.length < 2) return;
for (let i = 0; i < arr.length; i++) {
heapInsert(arr, i);
}
console.log(arr);
let heapSize = arr.length;
heapSize--;
[arr[0], arr[heapSize]] = [arr[heapSize], arr[0]];
while (heapSize > 0) {
heapify(arr, 0, heapSize);
heapSize--;
[arr[0], arr[heapSize]] = [arr[heapSize], arr[0]];
}
};
heapSort(arr);
console.log(arr);
堆排序-js实现
最新推荐文章于 2022-03-04 22:18:26 发布