用堆实现一个排序算法heap_sort(A),对数组A进行排序

    答案:

    1. function swap(A, i, j) {
    2. const t = A[i]
    3. A[i] = A[j]
    4. A[j] = t
    5. }
    6. class MaxHeap{
    7. constructor(data){
    8. this.list = data
    9. this.heapSize = data.length
    10. this.build()
    11. }
    12. build(){
    13. let i = Math.floor(this.heapSize/2) - 1
    14. while(i >= 0) {
    15. this.max_heapify(i--)
    16. }
    17. }
    18. extract() {
    19. if (this.heapSize === 0) return null
    20. const item = this.list[0]
    21. swap(this.list, 0, this.heapSize - 1)
    22. this.heapSize--
    23. this.max_heapify(0)
    24. return item
    25. }
    26. max_heapify(i) {
    27. const leftIndex = 2*i + 1
    28. const rightIndex = 2*i + 2
    29. let maxIndex = i
    30. if(leftIndex < this.heapSize && this.list[leftIndex] > this.list[maxIndex]) {
    31. maxIndex = leftIndex
    32. }
    33. if(rightIndex < this.heapSize && this.list[rightIndex] > this.list[maxIndex]) {
    34. maxIndex = rightIndex
    35. }
    36. if(i !== maxIndex) {
    37. swap(this.list, maxIndex, i)
    38. this.max_heapify(maxIndex)
    39. }
    40. }
    41. }
    42. function heap_sort(A){
    43. const heap = new MaxHeap(A)
    44. console.log(heap.list)
    45. while(heap.heapSize > 0){
    46. A[heap.heapSize-1] = heap.extract()
    47. }
    48. }