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.

Download Code

 
Kotlin offers a version that sorts the array between the specified range:

Download Code

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:

Download Code

 
You can also implement your custom comparator. Consider the following code, which is equivalent to the above code:

Download Code

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.

Download Code

 
To sort in descending order, use sortByDescending() function:

Download Code

4. Using sortDescending() function

Kotlin even has a native function, sortDescending(), for sorting an array in descending order according to their natural order.

Download Code

That’s all about in-place sorting an array in Kotlin.