Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort swift array and keep track of original index

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?

like image 671
user5672373 Avatar asked Dec 14 '22 03:12

user5672373


2 Answers

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]
like image 109
twiz_ Avatar answered Dec 30 '22 00:12

twiz_


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)!))
like image 27
ohr Avatar answered Dec 30 '22 00:12

ohr