scalasortingstable-sort

Scala: How to sort an array within a specified range of indices?


And I have a comparison function "compr" already in the code to compare two values.

I want something like this:

Sorting.stableSort(arr[i,j] , compr)

where arr[i,j] is a range of element in array.


Solution

  • Take the slice as a view, sort and copy it back (or take a slice as a working buffer).

    scala> val vs = Array(3,2,8,5,4,9,1,10,6,7)
    vs: Array[Int] = Array(3, 2, 8, 5, 4, 9, 1, 10, 6, 7)
    
    scala> vs.view(2,5).toSeq.sorted.copyToArray(vs,2)
    
    scala> vs
    res31: Array[Int] = Array(3, 2, 4, 5, 8, 9, 1, 10, 6, 7)
    

    Outside the REPL, the extra .toSeq isn't needed:

    vs.view(2,5).sorted.copyToArray(vs,2)
    

    Updated:

    scala 2.13.8> val vs = Array(3, 2, 8, 5, 4, 9, 1, 10, 6, 7)
    val vs: Array[Int] = Array(3, 2, 8, 5, 4, 9, 1, 10, 6, 7)
    
    scala 2.13.8> vs.view.slice(2,5).sorted.copyToArray(vs,2)
    val res0: Int = 3
    
    scala 2.13.8> vs
    val res1: Array[Int] = Array(3, 2, 4, 5, 8, 9, 1, 10, 6, 7)