排序数组和对应的数组

这个问题在这里已经有了答案:

  • 如何根据另一个数组的排序顺序对多个数组排序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)
    

    *这是通用的,因此可以与任何类型一起使用并让您提供条件


    使用快速排序:

    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提供的词典解决方案应该更快,更优雅。

    链接地址: http://www.djcxy.com/p/31681.html

    上一篇: Sort Array and a Corresponding Array

    下一篇: Swift inout parameter performance