Skip to content

Instantly share code, notes, and snippets.

@vderyagin
Created December 6, 2012 20:04
Show Gist options
  • Save vderyagin/4227841 to your computer and use it in GitHub Desktop.
Save vderyagin/4227841 to your computer and use it in GitHub Desktop.
quicksort in scala
def qSort[T <% Ordered[T]](list: List[T]): List[T] = list match {
case Nil => Nil
case l @ List(x) => l
case x :: xs => {
val (less, more) = xs.partition(_ < x)
qSort(less) ::: x :: qSort(more)
}
}
assert(qSort(Nil) == Nil)
assert(qSort(List(1)) == List(1))
assert(qSort(List(1, 2)) == List(1, 2))
assert(qSort(List(2, 1)) == List(1, 2))
assert(qSort(List(3, 2, 1)) == List(1, 2, 3))
assert(qSort(List(4,4,4,4,4,4,4,4,4,4,4,4)) == List(4,4,4,4,4,4,4,4,4,4,4,4))
assert(qSort(List(9,8,7,6,5,4,3,2,1,0)) == List(0,1,2,3,4,5,6,7,8,9))
assert(qSort(List('b', 'a', 'c')) == List('a', 'b', 'c'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment