Skip to content

Instantly share code, notes, and snippets.

@MrNocTV
Created March 11, 2019 08:37
Show Gist options
  • Save MrNocTV/34b0204948d95f01dcb018a817ddc520 to your computer and use it in GitHub Desktop.
Save MrNocTV/34b0204948d95f01dcb018a817ddc520 to your computer and use it in GitHub Desktop.
Max Heap array-based implementation using Scala
import java.io._
import scala.io._
import scala.collection.mutable._
import scala.math._
class MaxHeap(val maxSize: Int) {
private val heap = Array.fill[Int](maxSize)(0)
var size:Int = 0
private def parent(i: Int): Int = i / 2
private def leftChild(i: Int): Int = i * 2
private def rightChild(i: Int): Int = i * 2 + 1
private def isLeaf(i: Int): Boolean = {
if (i >= (size / 2) && i <= size)
return true
return false
}
private def swap(a: Int, b: Int) {
val temp = heap(a)
heap(a) = heap(b)
heap(b) = temp
}
private def maxHeapify(i: Int) : Unit = {
if (!isLeaf(i) && (heap(i) < heap(leftChild(i)) || heap(i) < heap(rightChild(i)))) {
if (heap(leftChild(i)) > heap(rightChild(i))) {
swap(i, leftChild(i))
maxHeapify(leftChild(i))
} else {
swap(i, rightChild(i))
maxHeapify(rightChild(i))
}
}
}
def insert(value: Int) {
size += 1
heap(size) = value
var cur = size
while (cur > 1 && heap(cur) > heap(parent(cur))) {
swap(cur, parent(cur))
cur = parent(cur)
}
}
def print() {
for(i <- 1 to (size / 2)) {
println("Parent: " + heap(i) + " left child: " + heap(leftChild(i)) + " right child: " + heap(rightChild(i)))
}
}
def extractMax(): Int = {
val max = heap(1)
heap(1) = heap(size)
size -= 1
maxHeapify(1)
max
}
def length(): Int = size
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment