Trying to implement Heap Sort in Scala
class HeapSort
{
private def swap(array: Array[Int], lhs: Int, rhs: Int) =
{
val tmp = array(lhs);
array(lhs) = array(rhs);
array(rhs) = tmp;
}
private def getParent(child: Int): Int = (child - 1) / 2;
private def getChildren(parent: Int): Tuple2[Int, Int] =
{
val base = parent * 2;
return (base + 1, base + 2);
}
private def swapLargestValue(array: Array[Int], setRoot: (Int) => Unit, root: Int, left: Int, right: Int): Boolean =
{
if (array(root) >= array(left) && array(root) >= array(right)) {
return true;
}
if (array(left) >= array(right)) {
swap(array, root, left);
setRoot(left);
}
else {
swap(array, root, right);
setRoot(right);
}
return false;
}
private def siftDown(array: Array[Int], begin: Int, end: Int): Unit =
{
var root = begin;
var (left, right) = getChildren(root);
while(left < end) {
if (swapLargestValue(array, root = _, root, left, if (right < end) right else left)) {
return;
}
val x = getChildren(root);
left = x._1;
right = x._2;
}
}
private def heapify(array: Array[Int], end: Int): Unit =
{
if (end == 0) {
return;
}
var start = getParent(end - 1);
while(start >= 0) {
siftDown(array, start, end);
start -= 1;
}
}
def heapSort(array: Array[Int]): Unit =
{
if (array.length <= 1) {
return;
}
heapify(array, array.length);
var end = array.length - 1;
while(end != 0) {
swap(array, 0, end);
siftDown(array, 0, end);
end -= 1;
}
}
}
object HS {
def main(args: Array[String]) {
var data = Array(5,6,7,2,3,4,8,9,1,4,6,2,8,5,4,3);
var hs = new HeapSort;
hs.heapSort(data);
println(data.deep.mkString(", "))
}
}
siftDown()
. It seems to be the standard name for that operation: stackoverflow.com/questions/34329942/… \$\endgroup\$