使用香草JavaScript实现堆排序
堆排序基本上是一种基于比较的排序算法。可以将其视为一种改进的选择排序-类似于该算法,它将输入分为已排序和未排序的区域,并通过提取目标(最大或最小)元素并将其移至已排序的区域来交互式地缩小未排序的区域地区。
示例
为此的代码将是-
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 ]