.sort()
Published Dec 2, 2024
Contribute to Docs
The .sort()
function in Kotlin sorts the elements of an array in ascending order in-place, meaning it rearranges the original array. It does not return a new array but modifies the existing one, making the change directly to the array.
Syntax
arrayName.sort()
arrayName
: Refers to the variable that holds the array to be sorted.
Example
This example demonstrates the use of .sort()
to sort the elements of an array in ascending order:
fun main() {val array = arrayOf(5, 2, 9, 1, 4)// Sort the array in ascending orderarray.sort()// Print the array contentsprintln(array.contentToString())}
The above code produces the following output:
[1, 2, 4, 5, 9]
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Kotlin on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn Kotlin
Learn Kotlin, the expressive, open-source programming language developed by JetBrains.Beginner Friendly9 hours