Created
March 5, 2014 06:06
-
-
Save rubanm/9362037 to your computer and use it in GitHub Desktop.
Sorting algorithms on top of OrderedList monoid
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
object OrderedListMonoid { | |
def zero: List[Int] = List[Int]() | |
def plus(left: List[Int], right: List[Int]): List[Int] = | |
(left, right) match { | |
case (Nil, r) => r | |
case (l, Nil) => l | |
case (lhead :: ltail, rhead :: rtail) => | |
if (lhead <= rhead) lhead :: plus(ltail, right) | |
else rhead :: plus(left, rtail) | |
} | |
} | |
def insertionSort(list: List[Int]): List[Int] = { | |
var sorted = OrderedListMonoid.zero | |
list.foreach { v => sorted = OrderedListMonoid.plus(sorted, List(v)) } | |
sorted | |
} | |
def mergeSort(list: List[Int]): List[Int] = { | |
if (list.length <= 1) { | |
list | |
} else { | |
val (left, right) = list.splitAt(list.length / 2) | |
OrderedListMonoid.plus(mergeSort(left), mergeSort(right)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment