11.10. Sorting Arrays

Problem

You want to sort the elements in an Array (or ArrayBuffer).

Solution

If you’re working with an Array that holds elements that have an implicit Ordering, you can sort the Array in place using the scala.util.Sorting.quickSort method. For example, because the String class has an implicit Ordering, it can be used with quickSort:

scala> val fruits = Array("cherry", "apple", "banana")
fruits: Array[String] = Array(cherry, apple, banana)

scala> scala.util.Sorting.quickSort(fruits)

scala> fruits
res0: Array[String] = Array(apple, banana, cherry)

Notice that quickSort sorts the Array in place; there’s no need to assign the result to a new variable.

This example works because the String class (via StringOps) has an implicit Ordering. Sorting.quickSort can also sort arrays with the base numeric types like Double, Float, and Int, because they also have an implicit Ordering.

Other solutions

If the type an Array is holding doesn’t have an implicit Ordering, you can either modify it to mix in the Ordered trait (which gives it an implicit Ordering), or sort it using the sorted, sortWith, or sortBy methods. These approaches are shown in Recipe 10.29.

Also, there are no unique sorting approaches for an ArrayBuffer, so see Recipe 10.29 for an example of how to sort it as well.

See Also

The Scaladoc for the Ordered and Ordering traits is very good. The header information in both documents shows good examples of the approaches shown in this recipe and Recipe 10.29.

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.