Which sorting is using for .sort(), .sortWith() etc methods?
val array = arrayOf(3,2,1)
Are there some differences in algorithms for arrays of different types and sizes?
To sort an Array in descending order in Kotlin, use Array. sortDescending() method. This method sorts the calling array in descending order in-place. To return the sorted array and not modify the original array, use Array.
The following collection types are relevant for Kotlin: List is an ordered collection with access to elements by indices – integer numbers that reflect their position. Elements can occur more than once in a list.
Just to extend on what Marko Toplnik said in the comment: Be careful how you create your arrays, because based on that, different sort
functions will be used.
val array = arrayOf(3,2,1)
array.sort()
which (in Kotlin/JVM) leads to:
public fun <T> Array<out T>.sort(): Unit {
if (size > 1) java.util.Arrays.sort(this)
}
https://github.com/JetBrains/kotlin/blob/04bbf2393684fb7f552da667e8f28dfc1f83bbfb/libraries/stdlib/jvm/src/generated/_ArraysJvm.kt#L1789-L1798
This will result in java.util.ComparableTimSort
being used (see the sort(Object[] a)
)
val array = intArrayOf(3,2,1)
array.sort()
which (in Kotlin/JVM) leads to:
public actual fun IntArray.sort(): Unit {
if (size > 1) java.util.Arrays.sort(this)
}
https://github.com/JetBrains/kotlin/blob/04bbf2393684fb7f552da667e8f28dfc1f83bbfb/libraries/stdlib/jvm/src/generated/_ArraysJvm.kt#L1729-L1734
This will result in java.util.DualPivotQuicksort
being used (see the sort(int[] a)
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With