Scala: reverse order of Sorting.quickSort?

2019-08-26 12:46发布

问题:

This answer explains how to reverse the order of sorting an array while using its built-in method .sortBy. How do I reverse the order of the sorting when using scala.util.Sorting.quickSort?

回答1:

Like so:

import scala.util.Sorting.quickSort

val a = Array(1, 2, 3)
quickSort[Int](a)(Ordering[Int].reverse)
//       ^---^ the most important bit
println(a.toVector) // Vector(3, 2, 1)

quickSort is a function that has overloads for Int, Float and Double, which don't let you specify ordering, and the generic one for any type [T] that has Ordering instance.

If you have an array of Int, Float or Double, overload resolution will prefer specialized versions, so you will not be able to pass Ordering manually unless you specify a type parameter (so compiler now only has one choice).

For arrays of things other than these three types (e.g. Longs), you can omit the type parameter, because there's only one valid option:

val b = Array(1L, 2L, 3L)
quickSort(b)(Ordering[Long].reverse)
println(b.toVector) // Vector(3, 2, 1)


回答2:

If you look up the type signature of quickSort you should find:

def quickSort[K](a: Array[K])(implicit arg0: math.Ordering[K]): Unit

Obviously this means that you can customize the behaviour by implementing an implicit Ordering[K] (or passing in one).

Example:

val a = Array(3, 4, 2, 3)
quickSort[Int](a)(Ordering.Int.reverse)


标签: scala sorting