2

Say I have and array [4, 1, 8, 5] and another array that corresponds to each object in the first array, say ["Four", "One", "Eight", "Five"]. How can I sort the first array in ascending order while also moving the corresponding object in the second array to the same index in Swift?

raginggoat
  • 3,570
  • 10
  • 48
  • 108
  • 3
    Why are you maintaining two arrays in the first place if they have mutual dependency? Why not make a dictionary like Key is 4 and value is Four? – NSNoob May 23 '16 at 11:55
  • I have one array that consists of dictionaries from JSON. I have another array that consists of ints calculated from values in the JSON dictionaries. I guess I could do the calculations then add a new key to each dictionary and sort that way. – raginggoat May 23 '16 at 11:58

2 Answers2

2

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

Or Ron
  • 2,313
  • 20
  • 34
0

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.

Community
  • 1
  • 1
Idan
  • 5,405
  • 7
  • 35
  • 52