<分区>
我正在尝试返回与排序值相对应的数组索引。例如,
let arr = [7, 10, -3]
let idxs = argsort(arr) // [2, 0, 1]
我的尝试有效但并不完美,并且仅适用于 CGFloat。我正在寻找一些方法来改进功能,使其通用且更易于阅读。代码看起来很难看,
func argsortCGFloat( a : [CGFloat] ) -> [Int] {
/* 1. Values are wrapped in (index, values) tuples */
let wrapped_array = Array(Zip2(indices(a),a))
/* 2. A comparator compares the numerical value from
two tuples and the array is sorted */
func comparator(a: (index : Int, value : CGFloat), b: (index : Int, value : CGFloat)) -> Bool {
return a.value < b.value
}
var values = sorted(wrapped_array, comparator)
/* 3. The sorted indexes are extracted from the sorted
array of tuples */
var sorted_indexes: [Int] = []
for pair in values {
sorted_indexes.append(pair.0)
}
return sorted_indexes
}