How to sort the part of an array in Scala

1 Answer

0 votes
object PartialSortExample {
  def main(args: Array[String]): Unit = {
    val arr = Array(15, 6, 19, 8, 3, 7, 9, 1, 4)

    // Extract the subrange (indices 2 to 6 inclusive)
    val subrange = arr.slice(2, 7).sorted

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

    // Print the updated list
    println(arr.mkString("[", ", ", "]"))
  }
}


 
 
/*
run:
  
[15, 6, 3, 7, 8, 9, 19, 1, 4]
  
*/

 



answered Aug 12, 2025 by avibootz
...