How do you write an idiomatic Scala Quicksort function?

Posted by Don Mackenzie on Stack Overflow See other posts from Stack Overflow or by Don Mackenzie
Published on 2010-06-02T22:09:03Z Indexed on 2010/06/02 22:14 UTC
Read the original article Hit count: 220

Filed under:

I recently answered a question with an attempt at writing a quicksort function in scala, I'd seen something like the code below written somewhere.

def qsort(l: List[Int]): List[Int] = {
  l match {
    case Nil         => Nil
    case pivot::tail => qsort(tail.filter(_ < pivot)) ::: pivot :: qsort(tail.filter(_ >= pivot))
  }
}

My answer received some constructive criticism pointing out that List was a poor choice of collection for quicksort and secondly that the above wasn't tail recursive.

I tried to re-write the above in a tail recursive manner but didn't have much luck. Is it possible to write a tail recursive quicksort? or, if not, how can it be done in a functional style? Also what can be done to maximise the efficiency of the implementation?

Thanks in advance.

© Stack Overflow or respective owner

Related posts about scala