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
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
-
can this work zipping more than two arrays? How can I unzip everything back to normal?Nicholas– Nicholas2015年03月12日 23:15:43 +00:00Commented 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.MirekE– MirekE2015年03月12日 23:50:49 +00:00Commented 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.Nicholas– Nicholas2015年03月13日 07:41:29 +00:00Commented Mar 13, 2015 at 7:41
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
lang-swift