Monday, August 29, 2011

Scala quicksort

Here's a version of quicksort in Scala that I took from the excellent "Scala by Example" pdf from the scala website. The main algorithm is intact; I just thought it would be nice to get a print out of the steps being performed. So basically the program has been changed to include a few extra variables so that their value can be printed to the console. The unsorted input array has been hard-coded into the program just to avoid writing additional code to parse input arguments.

If you have scala installed, you can copy and paste the code to a file, compile it (scalac filename), run (scala compiledfilename) and see the output. Enjoy!


object QuickSort {
def sort(xs: Array[Int]): Array[Int] = {
if (xs.length <= 1) xs
else {
val pivot = xs(xs.length / 2)
val lessThanPivot = xs filter (pivot >)
val equalToPivot = xs filter (pivot ==)
val greaterThanPivot = xs filter (pivot <)
println("Pivot for array [%s] is %d".format(xs.deep.mkString(" "),
pivot))
println("[%s] [%s] [%s]\n".format(lessThanPivot.deep.mkString(" "),
equalToPivot.deep.mkString(" "),
greaterThanPivot.deep.mkString(" ")))
Array.concat(sort(lessThanPivot), equalToPivot, sort(greaterThanPivot))
}
}
def main(args: Array[String]) {
val inputArray = Array(10,9,8,3,7,6,5,4,3,2,1)
println("Input Array : [%s]\n".format(inputArray.deep.mkString(" ")))
println("Sorted Array: [%s]".format(sort(inputArray).deep.mkString(" ")))
}
}

No comments: