Last active
March 5, 2018 20:56
-
-
Save taintech/12db269ff122263f809913df77a8ca47 to your computer and use it in GitHub Desktop.
Scala insertion sort implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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