Created
November 13, 2011 12:43
-
-
Save nartamonov/1362070 to your computer and use it in GitHub Desktop.
Selection sort in scala. Purely functional implementation with iterative behavior and using persistent collections.
This file contains hidden or 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 selectionSort[T <% Ordered[T]](seq: Seq[T]): Seq[T] = { | |
def pickMax(seq: Seq[T]): (T, Seq[T]) = | |
seq.tail.foldRight((seq.head, Seq.empty[T])) { | |
case (next, (max, passed)) => | |
if (next > max) | |
(next, max +: passed) | |
else | |
(max, next +: passed) | |
} | |
Iterator.iterate((Seq.empty[T], seq)) { case (sorted, seq) => | |
val (max, rest) = pickMax(seq) | |
(max +: sorted, rest) | |
} dropWhile { case (_, seq) => !seq.isEmpty } next() _1 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment