对swift数组进行排序并跟踪原始索引

use*_*373 3 arrays sorting swift

我想对一个快速数组进行排序并跟踪原始索引.例如: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]

有这么简单的方法吗?

twi*_*iz_ 9

最简单的方法是枚举.Enumerate按照它们出现的顺序为数组中的每个元素提供一个索引,然后您可以单独处理它们.

let sorted = arrayToSort.enumerate().sort({$0.element > $1.element})
Run Code Online (Sandbox Code Playgroud)

这导致[(.0 1,.1 5.5),(.0 3,.1 1.3),(.0 0,.1 1.2),(.0 2,.1 0.7)]

要获得索引排序:

let justIndices = sorted.map{$0.index}   // [1, 3, 0, 2]
Run Code Online (Sandbox Code Playgroud)


ohr*_*ohr 1

也许沿着这些思路

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)
Run Code Online (Sandbox Code Playgroud)

您还可以使用元组。

var indices = [(Int,Int)]()
indices.append((arrayToSort.indexOf(element)!,sortedArray.indexOf(element)!))
Run Code Online (Sandbox Code Playgroud)