How to sort the part of an array in Kotlin

1 Answer

0 votes
object PartialSortExample {
    @JvmStatic
    fun main(args: Array<String>) {
        val arr = arrayOf(15, 6, 19, 8, 3, 7, 9, 1, 4)

        // Extract the subrange (indices 2 to 6 inclusive)
        val subrange = arr.sliceArray(2..6).sortedArray()

        // Replace the original subrange with the sorted one
        for (i in subrange.indices) {
            arr[2 + i] = subrange[i]
        }

        // Print the updated list
        println(arr.joinToString(prefix = "[", separator = ", ", postfix = "]"))
    }
}


 
  
/*
run:

[15, 6, 3, 7, 8, 9, 19, 1, 4]

*/

 



answered Aug 13, 2025 by avibootz
...