在Swift中对2个链接数组进行排序?

时间:2018-05-02 14:49:26

标签: arrays swift sorting

我想将一个数组和“镜像”顺序更改排序到同一维度的另一个数组。

问题与此类似,但对于Swift语言: Better way to sort 2 "linked" arrays?

示例:

let arr1 = ["a", "b", "c", "d", "e"]
let arr2 = [1, 5, 9, 2, 3]
... //sort
//result == ["a", "d", "e", "b", c"]

我知道的近似解决方案:

for i in stride(from 0, to: arr2.count - 1, by: 1) {
  for j in stride(from i + 1, to: arr2.count, by: 1) {
    if arr2[i] > arr2[j] {
      ...//swap arr2[i] and arr2[j]
      ...//swap arr1[i] and arr1[j]
    }
  }
}

但他们为在Swift中使用数组进行高级处理添加了许多其他可能性。那么是否可以使用内部Swift功能简化此解决方案?

注意:arr1arr2作为单独的数组提供。

EDITED

是。您发现了类似的问题,但他们的标题很糟糕,并没有反映出作者需要的答案。换句话说,如果您删除/关闭我的问题,人们可能会继续再次询问,因为无法找到现有标题的内容!

1 个答案:

答案 0 :(得分:2)

  • zip阵列在一起
  • sort数组2的新数组
  • map数组到数组1

    let arr1 = ["a", "b", "c", "d", "e"]
    let arr2 = [1, 5, 9, 2, 3]
    
    let result = zip(arr1, arr2) // [("a", 1), ("b", 5), ("c", 9), ("d", 2), ("e", 3)]
                    .sorted(by: {$0.1 < $1.1}) // [("a", 1), ("d", 2), ("e", 3), ("b", 5), ("c", 9)]
                    .map{ $0.0 } // ["a", "d", "e", "b", "c"]