sorting - Swift 返回将对数组进行排序的索引(类似于 numpy argsort)

标签 sorting swift numpy

<分区>

我正在尝试返回与排序值相对应的数组索引。例如,

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
}

最佳答案

您可以通过创建索引数组并使用来自外部上下文的数组对它们进行排序来实现,如下所示:

func argsort<T:Comparable>( a : [T] ) -> [Int] {
    var r = Array(indices(a))
    r.sort({ a[$0] > a[$1] })
    return r
}

let arr = [7, 10, -3]
let idxs = argsort(arr)
println (idxs)

关于sorting - Swift 返回将对数组进行排序的索引(类似于 numpy argsort),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29183149/

相关文章:

python - cython 与 python 在 scipy.optimize.fsolve 中的不同结果

javascript - 按字母顺序排列的数组排序 - 小写在前

asp.net - 使用gridview asp.net进行排序和分页

php - 随机遍历数组而不提取重复值

macos - 访问 swift 数组时在运行时出现 EXC_BAD_ACCESS

ios - 使用 swiftDDP 将对象传递给 Meteor 方法

swift - 在 Swift 中的 AsynchronousRequest 之后,NSData 为 nil

python - 如何找到不同大小列表的中位数

python - 使用数组的 Numpy 索引

forms - 在 cfloop 之后对集合进行排序