Skip to content

Instantly share code, notes, and snippets.

@nartamonov
Created November 13, 2011 12:43
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 nartamonov/1362070 to your computer and use it in GitHub Desktop.
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.
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