Sorting in Kotlin

In Kotlin, we can use the standard library’s sorting functions for collections. Let’s look at sorting for built-in types first.

import kotlin.collections.sortedWith

fun main() {
    // Sorting functions work for any comparable type in Kotlin.
    // For strings, we can use the default sorting order.
    val strs = mutableListOf("c", "a", "b")
    strs.sort()
    println("Strings: $strs")

    // An example of sorting integers.
    val ints = mutableListOf(7, 2, 4)
    ints.sort()
    println("Ints:    $ints")

    // We can also check if a list is already in sorted order.
    val s = ints == ints.sorted()
    println("Sorted:  $s")
}

To run the program, save it as Sorting.kt and use the Kotlin compiler:

$ kotlinc Sorting.kt -include-runtime -d Sorting.jar
$ java -jar Sorting.jar
Strings: [a, b, c]
Ints:    [2, 4, 7]
Sorted:  true

In this Kotlin example:

  1. We use mutable lists (mutableListOf) to allow in-place sorting.
  2. The sort() function is called directly on the list, which sorts it in-place.
  3. For strings, the default lexicographical order is used.
  4. To check if a list is sorted, we compare it with its sorted version.

Kotlin’s standard library provides powerful and flexible sorting capabilities. The sortedWith() function can be used for custom sorting, which is equivalent to Go’s sort.Slice with a custom comparison function.

Next, we could explore more advanced sorting techniques in Kotlin, such as sorting with custom comparators or sorting objects by multiple properties.