I need help to fill in some blanks so that partition works upon calling partition(data,lower,upper). Although, I think that the if statement should be if (lower < upper-1) to avoid a wasted call. Also, sortRange must quick-sort the range [lower,upper). My question is, what would have to go in the (...) of def sort[A](data: Array[A])(...): Unit = {} to get it to work right and how could swap be implemented to make it work for swapping on an Array[A] with a range of ints?
object Quicksort {
def partition[A](data: Array[A], lower: Int, upper: Int)
(implicit comp: Ordering[A]): Int = {
val pivot = data(upper-1)
var mid = lower-1
for (i <- lower until upper-1) {
if (comp.lteq(data(i),pivot)) {
mid += 1
swap(data,mid,i)
}
}
swap(data,mid+1,upper-1)
mid+1
}
def sort[A](data: Array[A])(...): Unit = {
def sortRange(data: Array[A], lower: Int, upper: Int):
Unit = {
if(lower < upper) {
val pivotIndex = partition(data,lower,upper)
sortRange(data,lower,pivotIndex)
sortRange(data,pivotIndex+1,upper)
}
}
sortRange(data,0,data.length)
}
def main(args: Array[String]) : Unit = {
//Result of partition(data,lower,upper):
//sortRange results in quick-sorting the range: [lower,upper)
}
}
Since Quicksort is a sort-in-place algorithm (i.e. it's all about the side-effects), rather than pass the collection to be sorted, I'd want to "attach" the method to said collection.
I'd also want to remove all those pesky mutable variables.
implicit class QSort[A:Ordering](as: Array[A]) {
import Ordering.Implicits._
private def swap(x: Int, y: Int): Unit = {
val hold = as(x)
as(x) = as(y)
as(y) = hold
}
private def partition(lo: Int, hi: Int): Int =
((lo until hi).filter(as(_) < as(hi)) :+ hi)
.zipWithIndex.foldLeft(0){
case (_,(j,x)) => swap(j, lo+x); lo+x
}
private def quicksort(lo:Int, hi:Int): Unit =
if (lo < hi) {
val p = partition(lo, hi)
quicksort(lo, p-1)
quicksort(p+1, hi)
}
def qsort(): Unit = quicksort(0, as.length - 1)
}
testing:
val cs = Array('g','a','t','b','z','h')
cs.qsort() //: Unit
cs //: Array[Char] = Array(a, b, g, h, t, z)
val ns = Array(9,8,7,6,5,4,3,2,1)
ns.qsort() //: Unit
ns //: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9)