user5672373
user5672373

Reputation: 151

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?

Upvotes: 5

Views: 5185

Answers (4)

infinity_coding7
infinity_coding7

Reputation: 494

Thanks for the answer from @twiz_ and I think the syntax changed a bit in Swift3 and I just verified the following code in playground. It works

let arrayToSort = [1.2, 5.5, 0.7, 1.3]
let sorted = arrayToSort.enumerated().sorted(by: {$0.element > $1.element}) // [(1, 5.5), (3, 1.3), (0, 1.2), (2, 0.69999999999999996)]
let justIndices = sorted.map{$0.offset} // [1, 3, 0, 2]

Upvotes: 4

twiz_
twiz_

Reputation: 1198

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]

Upvotes: 12

keithbhunter
keithbhunter

Reputation: 12324

You can do this easily by using a struct to keep up with the index position.

struct Foo {
    var value: Double
    var position: Int
}

let arrayToSort = [Foo(value: 1.2, position: 0), Foo(value: 5.5, position: 1), Foo(value: 0.7, position: 2), Foo(value: 1.3, position: 3)]
let sortedArray = arrayToSort.sorted { $0.value > $1.value }
let indexPosition = sortedArray.map { $0.position }

Upvotes: 1

ohr
ohr

Reputation: 1727

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)!))

Upvotes: 1

Related Questions