Last active
November 20, 2016 21:00
-
-
Save calvinlfer/3e5a40906c809851108f8bdee6cf2816 to your computer and use it in GitHub Desktop.
Generically sort elements that have a concept of ordering using recursion
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 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