Sorting By Functions in Scala

Sometimes we’ll want to sort a collection by something other than its natural order. For example, suppose we wanted to sort strings by their length instead of alphabetically. Here’s an example of custom sorts in Scala.

import scala.util.Sorting

object SortingByFunctions {
  def main(args: Array[String]): Unit = {
    var fruits = Array("peach", "banana", "kiwi")

    // We implement a comparison function for string lengths.
    // Scala's `Ordering` is helpful for this.
    implicit val lenOrdering: Ordering[String] = Ordering.by(_.length)

    // Now we can call `scala.util.Sorting.quickSort` with this custom
    // ordering to sort `fruits` by name length.
    Sorting.quickSort(fruits)
    println(fruits.mkString(", "))

    // We can use the same technique to sort an array of
    // values that aren't built-in types.
    case class Person(name: String, age: Int)

    val people = Array(
      Person("Jax", 37),
      Person("TJ", 25),
      Person("Alex", 72)
    )

    // Sort `people` by age using `scala.util.Sorting.quickSort`.
    //
    // Note: if the `Person` class is large,
    // you may want the array to contain `Person` references instead
    // and adjust the sorting function accordingly. If in
    // doubt, benchmark!
    implicit val ageOrdering: Ordering[Person] = Ordering.by(_.age)
    Sorting.quickSort(people)
    println(people.mkString(", "))
  }
}

When you run this program, you’ll see:

$ scala SortingByFunctions.scala
kiwi, peach, banana
Person(TJ,25), Person(Jax,37), Person(Alex,72)

In this Scala example, we use scala.util.Sorting.quickSort along with Scala’s Ordering to achieve custom sorting. The implicit keyword is used to define custom orderings that the sorting function will use automatically.

For sorting strings by length, we create an implicit Ordering[String] that compares strings based on their length. For sorting Person objects by age, we create an implicit Ordering[Person] that compares based on the age field.

Scala’s approach to custom sorting is quite elegant and type-safe, leveraging the language’s powerful type system and implicits feature.