Kotlin – Sort an Array

Sort an Array in Kotlin

To sort an Array in ascending order in Kotlin, you can use Array.sort() function. Call the sort() function on the given array, and the function sorts the Array in-place in ascending order.

The syntax to sort the Array arr in ascending order is

arr.sort()

To sort an Array in descending order in Kotlin, you can use Array.sortDescending() function. Call the Array.sortDescending() function on the given array, and the function sorts the Array in-place in descending order.

The syntax to sort the Array arr in descending order is

arr.sortDescending()

Examples

Sort integer Array in ascending order

In the following program, we take an Arrays of integers: nums. Sort this Array in ascending order using Array.sort() function.

Kotlin Program

fun main(args: Array<String>) {
    var nums = arrayOf(5, 1, 8, 3, 7, 9, 4)
    nums.sort()
    println(nums.contentToString())
}

Output

[1, 3, 4, 5, 7, 8, 9]

Sort integer Array in descending order

In the following program, we take an Arrays of integers: nums. Sort this Array in descending order using Array.sortDescending() function.

Kotlin Program

fun main(args: Array<String>) {
    var nums = arrayOf(5, 1, 8, 3, 7, 9, 4)
    nums.sortDescending()
    println(nums.contentToString())
}

Output

[9, 8, 7, 5, 4, 3, 1]