排序数组和相应的数组

时间:2016-05-23 11:53:53

标签: arrays swift sorting

说我有和数组[4,1,8,5]和另一个对应于第一个数组中每个对象的数组,比如说["四","一个", "八","五"]。如何在升序中对第一个数组进行排序,同时将第二个数组中的相应对象移动到Swift中的相同索引?

2 个答案:

答案 0 :(得分:2)

听起来不是最佳做法,但这可以解决您的问题:

var numbers = [4,7,8,3]
var numbersString = ["Four","Seven","Eight","Three"]

func bubbleSort<T,Y>(inout numbers:[T],inout _ mirrorArray: [Y], _ comapre : (T,T)->(Bool)) -> () {
    let numbersLength = numbers.count

    for i in 0 ..< numbersLength {
        for j in 1 ..< numbersLength-i {
            if comapre(numbers[j-1],numbers[j]) {
                swap(&numbers[j-1], &numbers[j])
                swap(&mirrorArray[j-1], &mirrorArray[j])
            }
        }
    }
}

bubbleSort(&numbers,&numbersString) { (a, b) -> (Bool) in
    a<b
}
print(numbers,numbersString)

*这是通用的,因此适用于任何类型,并允许您提供条件

答案 1 :(得分:0)

使用quick sort

func quicksort_swift(inout a:[Int], inout b:[String], start:Int, end:Int) {
  if (end - start < 2){
    return
  }
  let p = a[start + (end - start)/2]
  var l = start
  var r = end - 1
  while (l <= r){
    if (a[l] < p){
      l += 1
      continue
    }
    if (a[r] > p){
      r -= 1
      continue
    }
    let t  = a[l]
    let t1 = b[l]
    a[l] = a[r]
    b[l] = b[r]
    a[r] = t
    b[r] = t1
    l += 1
    r -= 1
  }
  quicksort_swift(&a, b: &b, start: start, end: r + 1)
  quicksort_swift(&a, b: &b, start: r + 1, end: end)
}

虽然@NSNoob提供的词典解决方案应该更快更优雅。