二叉堆 (scala 实现)

class BinaryHeap (args:Int*) {
  var heap = new ArrayBuffer[Int]()
  args.foreach(insert)

  def insert(int: Int): Unit = {
    if (heap.size == 0) {
      heap += int
      return
    }
    heap+=int
    var parentIndex = parent(heap.size-1)
    var switchIndex = heap.size-1;
    while(heap(parentIndex)<int){
      swap(heap,parentIndex,switchIndex)
      switchIndex=parentIndex;
      parentIndex = parent(parentIndex)
    }
  }
  def extractMax():Int={
    val result = heap(0)
    heap(0) = heap(heap.size-1)
    heap.remove(heap.size-1)
    var node=0;
     while(node < heap.size){
        val maxChildNode =if(node*2>=heap.size || node*2+1>=heap.size){
          -1
        }else if (heap(2*node) >= heap(2*node+1)){
          2*node
        }  else {
          2*node+1
        };
        if(maxChildNode == -1){
          return result
        }
        swap(heap,node,maxChildNode)
        node = maxChildNode;
    }


    return result;
  }

  private[this] def parent(i:Int):Int={
    if(i==0) 0 else i/2
  }

  private[this] def swap(arr: ArrayBuffer[Int], a: Int, b: Int) = {
    val mid = arr(a)
    arr(a) = arr(b)
    arr(b) = mid
  }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值