Ensure stable sorting in MutableList.sort/sortWith

MutableList.sortWith now works correctly in JS_IR backend too

#KT-12473
This commit is contained in:
Ilya Gorbunov
2019-01-16 02:17:34 +03:00
parent 7191624a92
commit 56672c2564
7 changed files with 49 additions and 19 deletions
@@ -9,7 +9,6 @@ import test.assertStaticAndRuntimeTypeIs
import kotlin.test.*
import test.collections.behaviors.*
import test.comparisons.STRING_CASE_INSENSITIVE_ORDER
import kotlin.math.sin
import kotlin.random.Random
class CollectionTest {
@@ -829,6 +828,21 @@ class CollectionTest {
assertEquals(listOf("aa" to 20, "aa" to 3, "ab" to 3), data)
}
@Test fun sortStable() {
val keyRange = 'A'..'D'
for (size in listOf(10, 100, 2000)) {
val list = MutableList(size) { index -> Sortable(keyRange.random(), index) }
list.sorted().assertStableSorted()
list.sortedDescending().assertStableSorted(descending = true)
list.sort()
list.assertStableSorted()
list.sortDescending()
list.assertStableSorted(descending = true)
}
}
@Test fun sortedBy() {
assertEquals(listOf("two" to 3, "three" to 20), listOf("three" to 20, "two" to 3).sortedBy { it.second })
assertEquals(listOf("three" to 20, "two" to 3), listOf("three" to 20, "two" to 3).sortedBy { it.first })
@@ -862,6 +876,22 @@ class CollectionTest {
expect(listOf("BAD", "dad", "cat")) { data.sortedWith(comparator.reversed().reversed()) }
}
@Test fun sortByStable() {
val keyRange = 'A'..'D'
for (size in listOf(10, 100, 2000)) {
val list = MutableList(size) { index -> Sortable(keyRange.random(), index) }
list.sortedBy { it.key }.assertStableSorted()
list.sortedByDescending { it.key }.assertStableSorted(descending = true)
list.sortBy { it.key }
list.assertStableSorted()
list.sortByDescending { it.key }
list.assertStableSorted(descending = true)
}
}
@Test fun decomposeFirst() {
val (first) = listOf(1, 2)
assertEquals(first, 1)