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 } }
二叉堆 (scala 实现)
最新推荐文章于 2020-05-20 19:16:27 发布