js 封装 堆基本方法

一个基本的堆类实现,包括插入、删除和获取最大值的方法。以下是一个简单的最小堆的实现:

//封装堆类

class MinHeaap {
  constructor() {
    //实例一个数组存储堆数据
    this.heap = []
  }
  //获取父节点下标
  getParentIndex(index) {
    return Math.floor((index - 1) / 2);
  }

  //获取左节点下标
  getLeftChildIndex(index) {
    return index * 2 + 1
  }

  //获取右节点下标
  getRightChildIndex(index) {
    return index * 2 + 2
  }

  //获取堆长度
  size() {
    return this.heap.length;
  }

  //获取更节点值
  peak() {
    return this.heap[0]
  }

  //判空
  isEmpty() {
    return this.size()
  }

  //交换两节点
  swap(index1, index2) {
    let temp = this.heap[index1]
    this.heap[index1] = this.heap[index2]
    this.heap[index2] = temp
  }

  //插入值
  insert(val) {
    
    this.heap.push(val)
    this.shiftUp(this.heap.length - 1)
  }

  //获取堆中最小元素,
  getMin() {
    if (this.size() === 0) return null
    return this.heap[0]
  }

  //堆中移除最小元素并返回
  excractMin() {
    if (this.size() === 0) return null
    let minVal = this.heap[0]
    this.heap[0] = this.heap.pop()
    this.shiftDow(0)
    return minVal
  }


  //上浮操作,用于添加元素后调整对结构
  shiftUp(index) {
    while (index > 0 && this.heap[this.getParentIndex(index)] > this.heap[index]) {
      this.swap(this.getParentIndex(index), index)
      index = this.getParentIndex(index)
    }
  }

  //下浮操作,用于移除元素调整堆结构

  shiftDow(index) {
    let leftChildIndex = this.getLeftChildIndex(index);
    let rightChildIndex = this.getRightChildIndex(index);
    let copyIndex = index;
    if (leftChildIndex < this.size() && this.heap[leftChildIndex] < this.heap[copyIndex]) {
      copyIndex = leftChildIndex
    }
    if (rightChildIndex < this.size() && this.heap[rightChildIndex] < this.heap[copyIndex]) {
      copyIndex = rightChildIndex
    }
    if (copyIndex !== index) {
      this.swap(index, copyIndex)
      this.shiftDow(copyIndex)
    }
  }

}




//具体使用

let minHeap = new MinHeaap()

minHeap.insert(2)
minHeap.insert(8)
minHeap.insert(9)
minHeap.insert(1)
minHeap.insert(3)

console.log(minHeap.heap);
console.log(minHeap.getMin())
console.log(minHeap.size())
console.log(minHeap.excractMin())
console.log(minHeap.getMin())
console.log(minHeap.excractMin());
console.log(minHeap.heap);
console.log(minHeap.getMin());


述代码实现了一个最小堆,其中insert方法用于插入元素,extractMin方法用于删除并返回最小元素,getMin方法用于获取但不删除最小元素。堆的结构通过shiftUp和shiftDown方法进行维护。

你可能感兴趣的:(javascript,开发语言,ecmascript)