堆排序
var sortArray = function (nums) {
if (nums.length === 1) return nums;
return heapSort(nums);
function heapSort (arr) {
if (arr == null || arr.length < 2) return;
for (let i = 0; i < arr.length; i++) {
heapInsert(arr, i);
}
let heapSize = arr.length;
swap(arr, 0, --heapSize);
while (heapSize > 0) {
heapify(arr, 0, heapSize);
swap(arr, 0, --heapSize);
}
return arr;
}
function swap (arr, a, b) {
const temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
function heapInsert(arr, index) {
while (arr[index] > arr[Math.floor((index - 1) / 2)]) {
swap(arr, index, Math.floor((index - 1) / 2));
index = Math.floor((index - 1) / 2);
}
}
function heapify (arr, index, heapSize) {
let left = index * 2 + 1;
while (left < heapSize) {
let largest = (left + 1 < heapSize) && arr[left + 1] > arr[left] ? left + 1 : left;
if (arr[largest] > arr[index]) {
swap(arr, largest, index);
index = largest;
left = index * 2 + 1;
} else {
break;
}
}
}
}