Skip to content

Instantly share code, notes, and snippets.

@taintech
Last active March 5, 2018 20:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save taintech/12db269ff122263f809913df77a8ca47 to your computer and use it in GitHub Desktop.
Save taintech/12db269ff122263f809913df77a8ca47 to your computer and use it in GitHub Desktop.
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