Kotlin .sort()

MamtaWardhani's avatar
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.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn Kotlin, the expressive, open-source programming language developed by JetBrains.
    • Beginner Friendly.
      9 hours

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 order
array.sort()
// Print the array contents
println(array.contentToString())
}

The above code produces the following output:

[1, 2, 4, 5, 9]

All contributors

Contribute to Docs

Learn Kotlin on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn Kotlin, the expressive, open-source programming language developed by JetBrains.
    • Beginner Friendly.
      9 hours