In this tutorial, you shall learn how to sort a given array in descending order in Kotlin using different sorting methods available, with examples.

Kotlin – Array Sorting

Kotlin provides many methods via Array class to sort an Array. These methods help us to sort an array in-place, or return a sorted array; sort an array in ascending or descending order, sort based on a comparison function, etc.

In this tutorial, we will cover some of these methods which are most generally used.

  • Array.sort() – Sort in-place in ascending order
  • Array.sorted() – Return sorted Array
  • Array.sortDescending() – Sort in descending order
  • Array.sortBy() – Sort based on a comparison function

1. Array.sort()

sort() method sorts the calling Array in-place in ascending order.

In the following example, we take an array of integers, and sort them using sort() method.

Main.kt

fun main(args: Array<String>) {
    val arr = arrayOf(2, 4, 1, 3, 6, 5)
    arr.sort()
    for (x in arr) print("$x  ")
}

Output

1  2  3  4  5  6
ADVERTISEMENT

2. Array.sorted()

sorted() method returns the sorted Array. Original array is not modified.

In the following example, we take an array of integers, and sort them using sorted() method.

Main.kt

fun main(args: Array<String>) {
    val arr = arrayOf(2, 4, 1, 3, 6, 5)
    val result = arr.sorted()

    println("Original Array")
    for (x in arr) print("$x  ")
    println("\nSorted Array")
    for (x in result) print("$x  ")
}

Output

Original Array
2  4  1  3  6  5  
Sorted Array
1  2  3  4  5  6

3. Array.sortDescending()

sortDescending() method sorts the calling Array in-place in descending order.

In the following example, we take an array of integers, and sort them in descending order using sortDescending() method.

Main.kt

fun main(args: Array<String>) {
    val arr = arrayOf(2, 4, 1, 3, 6, 5)
    arr.sortDescending()
    for (x in arr) print("$x  ")
}

Output

6  5  4  3  2  1

4. Array.sortBy()

sortBy() method sorts the calling Array in-place in ascending order based on the specified comparison function.

In the following example, we take an array of strings, and sort them based on their length, in ascending order, using sortBy() method.

Main.kt

fun main(args: Array<String>) {
    val arr = arrayOf("apple", "fig", "banana", "kiwi")
    arr.sortBy { it.length }
    for (x in arr) print("$x  ")
}

Output

fig  kiwi  apple  banana

Length of "fig" is less than that of "kiwi".

Conclusion

In this Kotlin Tutorial, we learned how to sort an Array using different sorting methods of Array class covering different scenarios like order, comparison function, in-place sorting or not, etc., with examples.