To sort an array in ascending order in Kotlin, you can use the built-in sorting functions like `sorted()` or `sort()` depending on whether you want a new sorted array or to sort the array in-place.
In this example,
numbers
.sorted()
function to obtain a new sorted array.fun main() {
val numbers = arrayOf(5, 2, 8, 1, 9)
val sortedNumbers = numbers.sorted()
println("Sorted Array of Integers: ${sortedNumbers.joinToString()}")
}
Sorted Array of Integers: 1, 2, 5, 8, 9
In this example,
words
.sorted()
function to obtain a new sorted array.fun main() {
val words = arrayOf("apple", "banana", "cherry", "date")
val sortedWords = words.sorted()
println("Sorted Array of Strings: ${sortedWords.joinToString()}")
}
Sorted Array of Strings: apple, banana, cherry, date
In this tutorial, we learned How to Sort an Array in Ascending Order in Kotlin language with well detailed examples.