Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort an ArrayBuffer[Double] and save indices

Tags:

scala

Given an ArrayBuffer[Double], how can sort its elements with maintaining also their indices, e.g.

val arr ArrayBuffer[Double] = ArrayBuffer(4,5.3,5,3,8,9)

the result has to 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.

Thanks

like image 204
Momog Avatar asked Jan 25 '26 17:01

Momog


1 Answers

This is a one-liner:

val (addSorted, indices) = arr.zipWithIndex.sorted.unzip

Going step by step, zipWithIndex creates a collection of tuples with the 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 (which is almost certainly what you want, but you could also use sortBy(_._1) to be explicit about the fact that you want to sort by the values):

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 this collection of tuples into a tuple of collections, which you can deconstruct with val (addSorted, indices) = ....

like image 200
Travis Brown Avatar answered Jan 28 '26 08:01

Travis Brown



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!