使用原生 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 ]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP