Sort array in decreasing order in Kotlin
This article explores different ways to sort the array in decreasing order in Kotlin.
1. Using sortedArrayDescending() function
The standard solution to sort a primitive array or a generic array is using the sortedArrayDescending() function. It returns an array with all elements sorted in descending order. This is demonstrated below for an IntArray:
|
1 2 3 4 5 6 7 |
fun main() { val array: IntArray = intArrayOf(3, 1, 2, 5, 4) val sortedDesc = array.sortedArrayDescending() println(sortedDesc.contentToString()) // [5, 4, 3, 2, 1] } |
This works for both primitive and generic arrays. Note that this results in a new sorted array, and the original array remains unchanged.
|
1 2 3 4 5 6 7 |
fun main() { val array: Array<Int> = arrayOf(3, 1, 2, 5, 4) val sortedDesc = array.sortedArrayDescending() println(sortedDesc.contentToString()) // [5, 4, 3, 2, 1] } |
2. Using sortedByDescending() function
Another plausible, but a less efficient solution, is to sort the array in descending order using the sortedByDescending() function. This also works for both primitive and generic arrays and returns a “list” in reverse order. The following code demonstrates this:
|
1 2 3 4 5 6 |
fun main() { val array: IntArray = intArrayOf(3, 1, 2, 5, 4) val sortedDesc: List<Int> = array.sortedByDescending { it } println(sortedDesc) // [5, 4, 3, 2, 1] } |
You can invoke the corresponding to*Array() function to convert the list back into an array.
|
1 2 3 4 5 6 7 8 |
fun main() { val array: IntArray = intArrayOf(3, 1, 2, 5, 4) val sortedDesc = array .sortedByDescending { it } // List<Int> .toIntArray() // IntArray println(sortedDesc.contentToString()) // [5, 4, 3, 2, 1] } |
3. Using sortWith() function
Another good alternative is to use the sortWith() function to in-place sort a generic array according to the specified comparator. This assumes that all array elements are mutually comparable by the comparator. The following example demonstrates this:
|
1 2 3 4 5 6 7 |
fun main() { val array = arrayOf(3, 1, 2, 5, 4) array.sortWith(reverseOrder()) println(array.contentToString()) // [5, 4, 3, 2, 1] } |
This only works with a typed array, and won’t work with an array of primitives. To “inplace” sort a primitive array, use some standard sorting algorithm like Quicksort, Merge Sort, etc.
That’s all about sorting the array in decreasing order 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 :)