Heap sorting implemented in JavaScript

Time:2020-2-23

Heap sorting implemented in JavaScript

Heap sorting implemented in JavaScript

Heap sorting implemented in JavaScript

class Heap {
  constructor (data) {
    this.data = data
  }
  sort () {
    let iArr = this.data
    let n = iArr.length
    if (n <= 1) {
      return iArr
    } else {
      //The loop is to traverse every possible node to be adjusted, and the internal recursion of maxheap is to recover the damaged heap
      for (let i = Math.floor(n / 2); i >= 0; i--) {
        Heap.maxHeapify(iArr, i, n)
      }
      for (let j = 0; j < n; j++) {
        Heap.swap(iArr, 0, n - 1 - j)
        Heap.maxHeapify(iArr, 0, n - 1 - j - 1)
      }
      return iArr
    }
  }
  static swap (arr, a, b) {
    if (a === b) {
      return ''
    }
    // exchange
    let c = arr[a]
    arr[a] = arr[b]
    arr[b] = c
  }
  //Build maximum heap
  static maxHeapify (Arr, i, size) {
    // left node
    let l = i * 2 + 1
    // right node
    let r = i * 2 + 2
    let largest = i
    //Compare the parent node and the left node l to get the maximum
    if (l <= size && Arr[l] > Arr[largest]) {
      largest = l
    }
    // right node额最大值比较
    if (r <= size && Arr[r] > Arr[largest]) {
      largest = r
    }
    if (largest !== i) {
      Heap.swap(Arr, i, largest)
      Heap.maxHeapify(Arr, largest, size)
    }
  }
}

export default Heap