Skip to content

Instantly share code, notes, and snippets.

@silverprize
Created December 9, 2014 15:27
Show Gist options
  • Save silverprize/86fbd12dfe421a9534f6 to your computer and use it in GitHub Desktop.
Save silverprize/86fbd12dfe421a9534f6 to your computer and use it in GitHub Desktop.
Heapsort with scala
object HeapSort {
def sort(source: Array[Int]): Unit = {
buildHeap(source)
lineUp(source)
}
private def buildHeap(source: Array[Int]): Unit = {
def moveUp(source: Array[Int], idx: Int): Unit = {
if (idx > 0) {
val pIdx = Math.round(idx * 0.5f) - 1
if (source(pIdx) < source(idx)) {
swap(source, idx, pIdx)
moveUp(source, pIdx)
}
}
}
var idx = 1
while (idx < source.length) {
moveUp(source, idx)
idx += 1
}
}
private def lineUp(source: Array[Int]): Unit = {
def moveDown(source: Array[Int], len: Int, idx: Int): Unit = {
val leftChdIdx = idx * 2 + 1
val rightChdIdx = idx * 2 + 2
if (rightChdIdx < len && source(leftChdIdx) < source(rightChdIdx) && source(idx) < source(rightChdIdx)) {
swap(source, idx, rightChdIdx)
moveDown(source, len, rightChdIdx)
} else if (leftChdIdx < len && source(idx) < source(leftChdIdx)) {
swap(source, idx, leftChdIdx)
moveDown(source, len, leftChdIdx)
}
}
var idx = 1
while (idx <= source.length) {
swap(source, 0, source.length - idx)
moveDown(source, source.length - idx, 0)
idx += 1
}
}
private def swap(source: Array[Int], idx0: Int, idx1: Int): Unit = {
val tmp = source(idx0)
source(idx0) = source(idx1)
source(idx1) = tmp
}
}
object Main {
def main(args: Array[String]) {
def makeSource(size: Int, maxVal: Int): Array[Int] = {
val arr = new Array[Int](size)
for (i <- 0 until size) {
arr(i) = Random.nextInt(maxVal)
}
arr
}
val source = makeSource(20, 50)
source.foreach((v: Int) => print(v + " "))
println()
HeapSort.sort(source)
source.foreach((v: Int) => print(v + " "))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment