I can see there\'s a sorting object, Sorting
, with a quicksort method, quickSort
, on it.
What would be a code example of using it, sorting
While the accepted answer isn't wrong, the quicksort method provides more flexibility than that. I wrote this example for you.
import System.out.println
import scala.util.Sorting.quickSort
class Foo(x:Int) {
def get = x
}
//a wrapper around Foo that implements Ordered[Foo]
class OrdFoo(x:Foo) extends Ordered[Foo] {
def compare(that:Foo) = x.get-that.get
}
//another wrapper around Foo that implements Ordered[Foo] in a different way
class OrdFoo2(x:Foo) extends Ordered[Foo] {
def compare(that:Foo) = that.get-x.get
}
//an implicit conversion from Foo to OrdFoo
implicit def convert(a:Foo) = new OrdFoo(a)
//an array of Foos
val arr = Array(new Foo(2),new Foo(3),new Foo(1))
//sorting using OrdFoo
scala.util.Sorting.quickSort(arr)
arr foreach (a=>println(a.get))
/*
This will print:
1
2
3
*/
//sorting using OrdFoo2
scala.util.Sorting.quickSort(arr)(new OrdFoo2(_))
arr foreach (a=>println(a.get))
/*
This will print:
3
2
1
*/
This shows how implicit and explicit conversions from Foo to some class extending Ordered[Foo] can be used to get different sort orders.