使用原生 JavaScript 实现堆排序
javascriptweb developmentfront end technologyobject oriented programming更新于 2024/1/8 3:56:17
堆排序基本上是一种基于比较的排序算法。它可以被认为是一种改进的选择排序 − 像该算法一样,它将输入分为已排序区域和未排序区域,并通过提取目标(最大或最小)元素并将其移动到已排序区域来交互式地缩小未排序区域。
示例
其代码为 −
const constructHeap = (arr, ind) => {
let left = 2 * ind + 1;
let right = 2 * ind + 2;
let max = ind;
if (left < len && arr[left] > arr[max]) {
max = left;
}
if (right < len && arr[right] > arr[max]) {
max = right;
}
if (max != ind) {
swap(arr, ind, max);
constructHeap(arr, max);
}
}
function swap(arr, index_A, index_B) {
let temp = arr[index_A];
arr[index_A] = arr[index_B];
arr[index_B] = temp;
}
function heapSort(arr) {
len = arr.length;
for (let ind = Math.floor(len / 2); ind >= 0; ind −= 1) {
constructHeap(arr, ind);
}
for (ind = arr.length − 1; ind > 0; ind−−) {
swap(arr, 0, ind);
len−−;
constructHeap(arr, 0);
}
}
const arr = [3, 0, 2, 5, −1, 4, 1];
heapSort(arr);
console.log(arr);
var len;
输出
控制台中的输出将是 −
[ −1, 0, 1, 2, 3, 4, 5 ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

