From 2f570bd58ff03f1b252991d93ca26fa8d79c44ae Mon Sep 17 00:00:00 2001 From: Abduqodiri Qurbonzoda Date: Tue, 21 Apr 2020 18:45:35 +0300 Subject: [PATCH] Fix Array.sort failure in case of empty range (cherry picked from commit ae389ecdb0a1d2624d0f4c5d557a707693421570) --- .../kotlin/kotlin/collections/ArraySorting.kt | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/runtime/src/main/kotlin/kotlin/collections/ArraySorting.kt b/runtime/src/main/kotlin/kotlin/collections/ArraySorting.kt index 52dacac9648..1646c0121d6 100644 --- a/runtime/src/main/kotlin/kotlin/collections/ArraySorting.kt +++ b/runtime/src/main/kotlin/kotlin/collections/ArraySorting.kt @@ -11,7 +11,7 @@ private fun > mergeSort(array: Array, start: Int, endInclusi val buffer = arrayOfNulls(array.size) as Array val result = mergeSort(array, buffer, start, endInclusive) if (result !== array) { - result.forEachIndexed { i, v -> array[i] = v } + for (i in start..endInclusive) array[i] = result[i] } } @@ -64,7 +64,7 @@ private fun mergeSort(array: Array, start: Int, endInclusive: Int, compar val buffer = arrayOfNulls(array.size) as Array val result = mergeSort(array, buffer, start, endInclusive, comparator) if (result !== array) { - result.forEachIndexed { i, v -> array[i] = v } + for (i in start..endInclusive) array[i] = result[i] } } @@ -364,10 +364,11 @@ private fun quickSort( * Sorts the subarray specified by [fromIndex] (inclusive) and [toIndex] (exclusive) parameters * using the merge sort algorithm with the given [comparator]. */ -internal fun sortArrayWith( - array: Array, fromIndex: Int = 0, toIndex: Int = array.size, comparator: Comparator) { - @Suppress("UNCHECKED_CAST") - mergeSort(array as Array, fromIndex, toIndex - 1, comparator) +internal fun sortArrayWith(array: Array, fromIndex: Int, toIndex: Int, comparator: Comparator) { + if (fromIndex < toIndex - 1) { + @Suppress("UNCHECKED_CAST") + mergeSort(array as Array, fromIndex, toIndex - 1, comparator) + } } /** @@ -375,8 +376,10 @@ internal fun sortArrayWith( * [toIndex] (exclusive) parameters using the merge sort algorithm. */ internal fun > sortArray(array: Array, fromIndex: Int, toIndex: Int) { - @Suppress("UNCHECKED_CAST") - mergeSort(array as Array, fromIndex, toIndex - 1) + if (fromIndex < toIndex - 1) { + @Suppress("UNCHECKED_CAST") + mergeSort(array as Array, fromIndex, toIndex - 1) + } } /**