Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@rubanm
Created March 5, 2014 06:06
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 rubanm/9362037 to your computer and use it in GitHub Desktop.
Save rubanm/9362037 to your computer and use it in GitHub Desktop.
Sorting algorithms on top of OrderedList monoid
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