This is an excerpt from the Scala Cookbook (partially modified for the internet). This is one of the shortest recipes in the book, Recipe 11.10, “How to Sort Arrays in Scala”
You want to sort the elements in an
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
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)
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
Sorting.quickSort can also sort arrays with the base numeric types like
Int, because they also have an implicit
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
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.
The Scaladoc for the
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.
- The Sorting object
- The Ordering trait
- The Ordered trait
The Scala Cookbook
This tutorial is sponsored by the Scala Cookbook, which I wrote for O’Reilly:
You can find the Scala Cookbook at these locations: