用堆实现一个排序算法heap_sort(A),对数组A进行排序
答案:
function swap(A, i, j) {const t = A[i]A[i] = A[j]A[j] = t}class MaxHeap{constructor(data){this.list = datathis.heapSize = data.lengththis.build()}build(){let i = Math.floor(this.heapSize/2) - 1while(i >= 0) {this.max_heapify(i--)}}extract() {if (this.heapSize === 0) return nullconst item = this.list[0]swap(this.list, 0, this.heapSize - 1)this.heapSize--this.max_heapify(0)return item}max_heapify(i) {const leftIndex = 2*i + 1const rightIndex = 2*i + 2let maxIndex = iif(leftIndex < this.heapSize && this.list[leftIndex] > this.list[maxIndex]) {maxIndex = leftIndex}if(rightIndex < this.heapSize && this.list[rightIndex] > this.list[maxIndex]) {maxIndex = rightIndex}if(i !== maxIndex) {swap(this.list, maxIndex, i)this.max_heapify(maxIndex)}}}function heap_sort(A){const heap = new MaxHeap(A)console.log(heap.list)while(heap.heapSize > 0){A[heap.heapSize-1] = heap.extract()}}
