Quicksort in Scala
Friday, November 13th, 2009Scala allows to define very short and precise the intension of the programmer. To demonstrate this I use Quicksort as an Example.
The following is an implementation of quicksort in Scala.
package de.vogella.scala.quicksort
/* Quicksort in Scala */
class Quicksort {
def sort(a:Array[Int]): Array[Int] =
if (a.length < 2) a
else {
val pivot = a(a.length / 2)
sort (a filter (pivot>)) ++ (a filter (pivot == )) ++
sort (a filter(pivot <))
}
}
And a little test
package de.vogella.scala.quicksort
object Test {
def main(args: Array[String]) = {
val quicksort = new Quicksort
val a = Array(5, 3, 2, 2, 1, 1, 9, 39 ,219)
quicksort.sort(a).foreach(n=> (print(n), print (" " )))
}
}
To learn more about Scala check out this introduction tutorial: Scala development with Eclipse
Update: this example is similar to the quicksort example from the excellent online Scala by Example book. Caution: The link is a pdf document.