gromyk
gromyk

Reputation: 610

What kind of sorting does Kotlin use by default?

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?

Upvotes: 16

Views: 6198

Answers (1)

Bartek Lipinski
Bartek Lipinski

Reputation: 31458

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))

Upvotes: 12

Related Questions