In-place sort an array in Kotlin
This article explores different ways to in-place sort an array in Kotlin. The sorting should be stable, i.e., equal elements preserve their relative order after sorting.
1. Using sort() function
The standard way to sort array in-place in Kotlin is with the sort() function. The sorting is done according to the natural ordering of its elements.
|
1 2 3 4 5 6 |
fun main() { val arr = arrayOf(4, 2, 1, 5, 3) arr.sort() println(arr.contentToString()) // [1, 2, 3, 4, 5] } |
Kotlin offers a version that sorts the array between the specified range:
|
1 2 3 4 5 6 7 8 |
fun main() { val arr = arrayOf(4, 2, 1, 5, 3) // sort elements between index 1 and 3 arr.sort(1, 3) println(arr.contentToString()) // [4, 1, 2, 5, 3] } |
2. Using sortWith() function
You can sort the array according to the order specified by a comparator using the sortWith() function provided that all array elements are mutually comparable by the comparator.
For example, the following code sorts the integer array in descending order using a comparator:
|
1 2 3 4 5 6 |
fun main() { val arr = arrayOf(4, 2, 1, 5, 3) arr.sortWith(Comparator.reverseOrder()) println(arr.contentToString()) // [5, 4, 3, 2, 1] } |
You can also implement your custom comparator. Consider the following code, which is equivalent to the above code:
|
1 2 3 4 5 6 |
fun main() { val arr = arrayOf(4, 2, 1, 5, 3) arr.sortWith(Comparator{ o1, o2 -> o2.compareTo(o1) }) println(arr.contentToString()) // [5, 4, 3, 2, 1] } |
3. Using sortBy() function
The sortBy() function in-place sorts the array elements according to the natural sort order of the value returned by the specified selector function.
|
1 2 3 4 5 6 |
fun main() { val arr = arrayOf(4, 2, 1, 5, 3) arr.sortBy { it } println(arr.contentToString()) // [1, 2, 3, 4, 5] } |
To sort in descending order, use sortByDescending() function:
|
1 2 3 4 5 6 |
fun main() { val arr = arrayOf(4, 2, 1, 5, 3) arr.sortByDescending { it } println(arr.contentToString()) // [5, 4, 3, 2, 1] } |
4. Using sortDescending() function
Kotlin even has a native function, sortDescending(), for sorting an array in descending order according to their natural order.
|
1 2 3 4 5 6 |
fun main() { val arr: Array<Int> = arrayOf(4, 2, 1, 5, 3) arr.sortDescending() println(arr.contentToString()) // [5, 4, 3, 2, 1] } |
That’s all about in-place sorting an array in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)