数据结构-堆
function buildMaxHeap(nums) {
let len = nums.length;
for(let i = Math.floor(len/2); i >= 0; i--) {
shiftDown(nums, len, i);
}
}
function insert(nums, data) {
nums.push(data);
fixUp(nums, nums.length - 1);
}
function shiftUp(nums, curIndex) {
let parentIndex = Math.floor(curIndex/2);
while(parentIndex >= 0) {
if(nums[parentIndex] < nums[curIndex]) {
swap(nums, parentIndex, curIndex);
curIndex = parentIndex;
parentIndex = Math.floor(curIndex/2)
} else {
break;
}
}
}
function remove(nums, len) {
if(len < 2) return;
swap(nums, 0, nums.length -1)
shiftDown(nums, len-1, 0)
}
function shiftDown(nums, len, curIndex) {
let maxChildIndex = 2 * curIndex + 1;
while(maxChildIndex < len) {
if(maxChildIndex + 1 < len && nums[maxChildIndex] < nums[maxChildIndex+1]) {
maxChildIndex++;
}
if(nums[maxChildIndex] > nums[curIndex]) {
swap(nums, curIndex, maxChildIndex);
curIndex = maxChildIndex;
maxChildIndex = 2 * curIndex + 1;
}else {
break;
}
}
}
function heapSort(nums) {
buildMaxHeap(nums);
let len = nums.length;
for(let i = len-1; i >= 0; i--) {
swap(nums, 0, i);
shiftDown(nums, i, 0);
}
}
function swap(nums, index1, index2) {
let temp = nums[index1];
nums[index1] = nums[index2];
nums[index2] = temp;
}
let arr1 = [10, 9, 8, 11, 12];
heapSort(arr1);
console.log(arr1);