I would to sort a swift array and keep track of the original indices. For example: arrayToSort = [1.2, 5.5, 0.7, 1.3]
indexPosition = [0, 1, 2, 3]
sortedArray = [5.5, 1.3, 1.2, 0.7]
indexPosition = [1, 3, 0, 2]
Is there an easy way of doing this?
Easiest way is with enumerate. Enumerate gives each element in the array an index in the order they appear and you can then treat them separately.
let sorted = arrayToSort.enumerate().sort({$0.element > $1.element})
this results in [(.0 1, .1 5.5), (.0 3, .1 1.3), (.0 0, .1 1.2), (.0 2, .1 0.7)]
To get the indices sorted:
let justIndices = sorted.map{$0.index} // [1, 3, 0, 2]
Perhaps something along these lines
let arrayToSort = [1.2, 5.5, 0.7, 1.3]
var oldIndices = [Int]()
let sortedArray = arrayToSort.sort { $0 > $1 }
var newIndices = [Int]()
for element in arrayToSort
{
oldIndices.append(arrayToSort.indexOf(element)!)
newIndices.append(sortedArray.indexOf(element)!)
}
print(oldIndices)
print(newIndices)
You could also use tuples.
var indices = [(Int,Int)]()
indices.append((arrayToSort.indexOf(element)!,sortedArray.indexOf(element)!))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With