Skip to content

Instantly share code, notes, and snippets.

@jthoenes
Created October 22, 2010 22:11
Show Gist options
  • Save jthoenes/641480 to your computer and use it in GitHub Desktop.
Save jthoenes/641480 to your computer and use it in GitHub Desktop.
Insertion Sort Implementations in Scala
def insertionSort(unsortedList : List[String]) = {
val F = unsortedList.toArray
for(i <- (2 until F.length)){
val m = F(i)
var j = i;
while(j > 1 && !sorted){
if (F(j-1) >= m) {
F(j) = F(j-1)
j -= 1
}
}
F(j) = m
}
F.toList
}
// Note:
// This algorithm has been transcribed from:
// Saake and Sattler. "Algorithmen und Datenstrukturen. Eine Einführung in Java".
// dpunkt.verlag Heidelberg, 2004. page 123f
def insertionSort(source : List[String]) = {
var sorted = List(source.head)
var unsorted = source.tail
while(unsorted.tail != Nil){
val index = sorted.indexWhere( _ > unsorted.head)
if(index < 0){
sorted = sorted ::: List(unsorted.head)
}
else {
sorted = sorted.take(index) ::: unsorted.head :: sorted.drop(index)
}
unsorted = unsorted.tail
}
sorted
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment