Sorting in Scala

Our example demonstrates sorting in Scala. We’ll look at sorting for built-in types first.

import scala.collection.mutable.ArrayBuffer

object Sorting {
  def main(args: Array[String]): Unit = {
    // Sorting functions work for any type that has an implicit Ordering.
    // For a list of types with default Orderings, see scala.math.Ordering.

    val strs = ArrayBuffer("c", "a", "b")
    scala.util.Sorting.quickSort(strs)
    println(s"Strings: ${strs.mkString("[", ", ", "]")}")

    // An example of sorting integers.
    val ints = ArrayBuffer(7, 2, 4)
    scala.util.Sorting.quickSort(ints)
    println(s"Ints:    ${ints.mkString("[", ", ", "]")}")

    // We can also check if a sequence is already in sorted order.
    val s = ints.sliding(2).forall { case Seq(a, b) => a <= b }
    println(s"Sorted:  $s")
  }
}

To run the program, save it as Sorting.scala and use scala:

$ scala Sorting.scala
Strings: [a, b, c]
Ints:    [2, 4, 7]
Sorted:  true

In this Scala example:

  1. We use ArrayBuffer as a mutable sequence, which is similar to slices in other languages.

  2. The scala.util.Sorting.quickSort method is used to sort the sequences in-place.

  3. To check if a sequence is sorted, we use the sliding method to compare adjacent pairs.

  4. Scala’s string interpolation (s"...") is used for formatting output strings.

  5. The mkString method is used to convert sequences to strings for printing.

Note that Scala provides powerful sorting capabilities through its collections library, including methods like sorted and sortWith for immutable collections, which weren’t showcased in this basic example.