Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 963
gromyk Avatar asked Oct 24 '18 08:10

gromyk


People also ask

How does Kotlin sort in descending order?

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.

Is Kotlin list ordered?

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.


Video Answer


1 Answers

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

like image 111
Bartek Lipinski Avatar answered Oct 13 '22 20:10

Bartek Lipinski