How to sort ArrayBuffer [Double] and preserve indices
Given ArrayBuffer [Double], how can its elements be sorted while preserving their indices as well, eg.
val arr ArrayBuffer[Double] = ArrayBuffer(4,5.3,5,3,8,9)
the result should be:
arrSorted = ArrayBuffer(3,4,5,5.3,8,9)
indices = Arraybuffer(3,0,2,1,4,5) //here the data structure doesn't matter, it can be Array, List, Vector, etc.
thank
source to share
This is a one-liner:
val (addSorted, indices) = arr.zipWithIndex.sorted.unzip
Step by step, zipWithIndex
creates a set of tuples with an index as the second value in each tuple:
scala> println(arr.zipWithIndex)
ArrayBuffer((4.0,0), (5.3,1), (5.0,2), (3.0,3), (8.0,4), (9.0,5))
sorted
sorts these tuples lexicographically (this is almost certainly what you want, but you can also use sortBy(_._1)
to be explicit about what you want to sort by value):
scala> println(arr.zipWithIndex.sorted)
ArrayBuffer((3.0,3), (4.0,0), (5.0,2), (5.3,1), (8.0,4), (9.0,5))
unzip
then turns that set of tuples into a tuple of collections that you can deconstruct with val (addSorted, indices) = ...
.
source to share