How to sort Arrays in Scala

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”

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.

  • 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:

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.