Skip to content

Instantly share code, notes, and snippets.

@calvinlfer
Last active November 20, 2016 21:00
Show Gist options
  • Select an option

  • Save calvinlfer/3e5a40906c809851108f8bdee6cf2816 to your computer and use it in GitHub Desktop.

Select an option

Save calvinlfer/3e5a40906c809851108f8bdee6cf2816 to your computer and use it in GitHub Desktop.
Generically sort elements that have a concept of ordering using recursion
def sort[T](input: List[T])(implicit ordering: Ordering[T]): List[T] = {
def inner(input: List[T], output: List[T]): List[T] =
(input, output) match {
case (Nil, out) => out
case (head :: tail, Nil) => inner(tail, head :: Nil)
case (iHead :: iTail, oHead :: oTail) if ordering.lteq(iHead, oHead) =>
inner(iTail, iHead :: oHead :: oTail)
case (iHead :: iTail, oHead :: oTail) =>
// in the case the input head gt output head then in the output list
// place oHead before iHead and you need to recursively call
// inner(iHead :: Nil, oTail) to get iHead placed correctly in the
// output list
inner(iTail, oHead :: inner(iHead :: Nil, oTail))
}
inner(input, Nil)
}
sort(list)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment