Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Scala insertion sort implementation
import scala.annotation.tailrec
object sortings {
def insertionSort(ar: Array[Int]): Array[Int] = {
@tailrec
def loop(i: Int, key: Int): Int =
if (i < 0 || ar(i) < key) i + 1
else {
ar(i + 1) = ar(i)
loop(i - 1, key)
}
for (i <- ar.indices.drop(1)) {
val key = ar(i)
val j = loop(i - 1, key)
ar(j) = key
}
ar
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment