-1

I have two arrays A and B. I was wondering what is the most efficient implementation for sorting array A and changing B according to the sorting indices of A.

I've worked out the following so far:

 var A = [5.0, 3.0, 7.0, 0.0, 2.0]
 var B = [3.0, 4.0, 5.0, 6.0, 7.0]
 var C = B
 let idxs = sorted(indices(A)) { A[0ドル] < A[1ドル] }
 println(idxs)
 for i in 0...A.count-1 {
 C[i] = B[idxs[i]]
 }
 println(C)
asked Mar 12, 2015 at 22:43

2 Answers 2

0

You could zip the two arrays together and sort by the first item:

var a = [5.0, 3.0, 7.0, 0.0, 2.0]
var b = [3.0, 4.0, 5.0, 6.0, 7.0]
var c = Array(zip(a, b)) // [(5.0, 3.0), (3.0, 4.0), (7.0, 5.0), (0.0, 6.0), (2.0, 7.0)]
c.sort { 0ドル.0 < 1ドル.0 } // [(0.0, 6.0), (2.0, 7.0), (3.0, 4.0), (5.0, 3.0), (7.0, 5.0)]
answered Mar 12, 2015 at 22:54
3
  • can this work zipping more than two arrays? How can I unzip everything back to normal? Commented Mar 12, 2015 at 23:15
  • No, zip works with two arrays. Obviously, you could create array of tuples with more than two elements manually. You could unzip the array with map, but the idea here was to keep all arrays together, if possible. Commented Mar 12, 2015 at 23:50
  • I'm working with more than two arrays. Your solution is nice but does not suit my problem. Thanks anyway. Commented Mar 13, 2015 at 7:41
0

Here is the solution I proposed for a similar question :

How to sort 1 array in Swift / Xcode and reorder multiple other arrays by the same keys changes

var names = [ "Paul", "John", "David" ]
var ages = [ 35, 42, 27 ]
let newOrder = names.enumerate().sort({0ドル.1<1ドル.1}).map({0ドル.0})
names = newOrder.map({names[0ドル]})
ages = newOrder.map({ages[0ドル]})
answered Feb 9, 2016 at 20:36

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.