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:

Download Code

 
This works for both primitive and generic arrays. Note that this results in a new sorted array, and the original array remains unchanged.

Download Code

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:

Download Code

 
You can invoke the corresponding to*Array() function to convert the list back into an array.

Download Code

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:

Download Code

 
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.