算法-排序-堆排序

(本文内容来自百度百科)

    原理及简介 地址: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())

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容