How to sort a Scala Array

Scala FAQ: How do I sort the elements in an Array in Scala?

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 fruits 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 that 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 How to sort a sequence (Seq, List, ArrayBuffer, Vector) in Scala.

Also, despite their names, an ArrayBuffer is very different from an Array, and you don’t sort it in the same way. See the How to sort a sequence in Scala recipe for how to sort an ArrayBuffer.

See Also

See the scala.util.Sorting object documentation for more details on using the quickSort method, and other sorting methods.