In this tutorial, you shall learn how to sort an array of integers in Kotlin, using Array.sort() method, with examples.

Kotlin – Sort Array of Integers

To sort an Array of Integers in Kotlin, use Array.sort() method. sort() method sorts the calling array in-place in ascending order. To sort Integer Array in descending order, call sortDescending() method on this Array.

Syntax

The syntax to call sort() method on Array arr is

arr.sort()

The syntax to call sortDescending() method on Array arr is

arr.sortDescending()
ADVERTISEMENT

Examples

Sort in Ascending Order

In the following example, we take an array of integers, and sort them in ascending order in-place 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

Sort in Descending Order

In the following example, we take an array of integers, and sort them in descending order in-place 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

Conclusion

In this Kotlin Tutorial, we learned how to sort an Integer Array in ascending or descending order using sort() or sortDescending() methods respectively, with examples.