I need to sort an array of pairs by second element. How do I pass comparator for my pairs to the quickSort function?
I’m using the following ugly approach now:
type AccResult = (AccUnit, Long) // pair
class Comparator(a:AccResult) extends Ordered[AccResult] {
def compare(that:AccResult) = lessCompare(a, that)
def lessCompare(a:AccResult, that:AccResult) = if (a._2 == that._2) 0 else if (a._2 < that._2) -1 else 1
}
scala.util.Sorting.quickSort(data)(d => new Comparator(d))
Why is quickSort designed to have an ordered view instead of usual comparator argument?
Scala 2.7 solutions are preferred.
Ok, I’m not sure exactly what you are unhappy about what you are currently doing, but perhaps all you are looking for is this?
If, on the other hand, the problem is that the tuple is
Orderedand you want a different ordering, well, that’s why it changed on Scala 2.8.* EDIT *
Ouch! Sorry, I only now realize you said you preferred Scala 2.7 solutions. I have editted this answer soon to put the solution for 2.7 above. What follows is a 2.8 solution.
Scala 2.8 expects an
Ordering, not anOrdered, which is a context bound, not a view bound. You’d write your code in 2.8 like this:Or maybe just:
And use it like:
On the other hand, the usual way to do sort in Scala 2.8 is just to call one of the sorting methods on it, such as: