(本文内容来自百度百科)
原理及简介 地址:https://baike.baidu.com/item/堆排序/2840151?fr=aladdin
JavaScript
Array.prototype.buildMaxHeap = function(){
for(let i = Math.floor(this.length/2)-1; i>=0 ; i--){
this.heapAdjust(i, this.length)
}
}
Array.prototype.swap = function(i, j){
let tmp = this[i]
this[i] = this[j]
this[j] = tmp
}
Array.prototype.headSort = function(){
this.buildMaxHeap()
for(let i = this.length - 1; i > 0 ; i--){
this.swap(0, i)
this.heapAdjust(0, i)
}
}
Array.prototype.heapAdjust = function(i, j){
let largest = i
let left = 2*i + 1
let right = 2*i + 2
if(left < j && this[largest] < this[left]){
largest = left
}
if(right < j && this[largest] < this[right]){
largest = right
}
if(largest != i){
this.swap(i, largest)
this.heapAdjust(largest, j)
}
}
let a = new Array()
a = [2, 3, 89, 57, 23, 72, 43, 105]
console.log(a.headSort())