Home > Software engineering >  How to efficiently sort two arrays based on the values in one of them?
How to efficiently sort two arrays based on the values in one of them?

Time:06-11

If I have two arrays:

a = [  1,   4,   3,   2]
b = ['z', 'w', 'x', 'y']

and I want to sort both a and b based on the values from a, i.e.:

[  1,  2,  3,  4]      # a 
['z','y','x','w']      # b

What is an efficient/idiomatic way to do this?

CodePudding user response:

With two distinct vectors I do not know if this is possible.

I would use sortperm that returns a permutation vector p that puts a[p] in sorted order

julia> p=sortperm(a)
4-element Vector{Int64}:
 1
 4
 3
 2

julia> a[p]
4-element Vector{Int64}:
 1
 2
 3
 4

julia> b[p]
4-element Vector{Char}:
 'z': ASCII/Unicode U 007A (category Ll: Letter, lowercase)
 'y': ASCII/Unicode U 0079 (category Ll: Letter, lowercase)
 'x': ASCII/Unicode U 0078 (category Ll: Letter, lowercase)
 'w': ASCII/Unicode U 0077 (category Ll: Letter, lowercase)

If performance is important you can also use sortperm! that allows using a preallocated permutation vector p.


Note: if you have a matrix you can use sortslices

julia> M=hcat(a,b)
4×2 Matrix{Any}:
 1  'z'
 4  'w'
 3  'x'
 2  'y'

julia> sortslices(M,dims=1,by=x->x[1])
4×2 Matrix{Any}:
 1  'z'
 2  'y'
 3  'x'
 4  'w'
  • Related