Sort Array and a Corresponding Array

This question already has an answer here:

  • How can I sort multiple arrays based on the sorted order of another array 2 answers

  • Doesn't sound like best practice but this will solve your problem:

    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)
    

    *This is generic therefore will work with any type and let you supply the condition


    Using 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)
    }
    

    Although, the dictionary solution offered by @NSNoob, should be faster and more elegant.

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

    上一篇: Swift与Kotlin在排序数组上的表现

    下一篇: 排序数组和对应的数组