summaryrefslogtreecommitdiff
path: root/docs/examples/sort2.scala
blob: e0016088bbf38dd967a14845ed7e241d046fc319 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package examples

object sort2 {

  def sort(a: List[Int]): List[Int] = {
    if (a.length < 2)
      a
    else {
      val pivot = a(a.length / 2)
      def lePivot(x: Int) = x < pivot
      def gtPivot(x: Int) = x > pivot
      def eqPivot(x: Int) = x == pivot
      sort(a filter lePivot) :::
           (a filter eqPivot) :::
           sort(a filter gtPivot)
    }
  }

  def main(args: Array[String]) {
    val xs = List(6, 2, 8, 5, 1, 8)
    println(xs)
    println(sort(xs))
  }

}