Created
October 22, 2010 22:11
-
-
Save jthoenes/641480 to your computer and use it in GitHub Desktop.
Insertion Sort Implementations in Scala
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
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 |
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
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