To sort an array in Kotlin, you can use the sortedArray()
function for ascending order and sortedArrayDescending()
function for descending order.
In this example,
numbers
with values 5, 2, 8, 1, 6.sortedArray()
function on the array to sort it in ascending order and store the sorted array in sortedNumbers
variable.sortedArray()
function sorts the array elements in ascending order.sortedNumbers
to standard output.fun main() {
val numbers = intArrayOf(5, 2, 8, 1, 6)
val sortedNumbers = numbers.sortedArray()
println("Sorted array in ascending order: ${sortedNumbers.contentToString()}")
}
Sorted array in ascending order: [1, 2, 5, 6, 8]
In this example,
numbers
with values 5, 2, 8, 1, 6.sortedArrayDescending()
function on the array to sort it in descending order and store the sorted array in sortedNumbers
variable.sortedArrayDescending()
function sorts the array elements in descending order.sortedNumbers
to standard output.fun main() {
val numbers = intArrayOf(5, 2, 8, 1, 6)
val sortedNumbers = numbers.sortedArrayDescending()
println("Sorted array in descending order: ${sortedNumbers.contentToString()}")
}
Sorted array in descending order: [8, 6, 5, 2, 1]
In this tutorial, we learned How to Sort an Array in Kotlin language with well detailed examples.