Created
November 20, 2016 20:51
-
-
Save calvinlfer/0205d0da39d188553e47f1a0d2bd8836 to your computer and use it in GitHub Desktop.
Generic merge sort based on elements having an Ordered typeclass implementation
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 mergeSort[T](list: List[T])(implicit ordering: Ordering[T]): List[T] = { | |
def merge(l: List[T], r: List[T]): List[T] = | |
(l, r) match { | |
case (lHead:: lTail, rHead :: rTail) if ordering.lteq(lHead, rHead) => lHead :: merge(lTail, r) | |
case (lHead:: lTail, rHead :: rTail) => rHead :: merge(l, rTail) | |
case (x, Nil) => x | |
case (Nil, y) => y | |
case (Nil, Nil) => Nil | |
} | |
val halfway = list.length / 2 | |
if (halfway == 0) list // list is empty or list is single value | |
else { | |
val (left, right) = list.splitAt(halfway) | |
merge(mergeSort(left), mergeSort(right)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Tail recursive
merge