Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Array by Order of another Array

Tags:

julia

I have

a = ["B", "C", "A"]

and

b = [7, 10, 5]

How can I sort a by the order of the elements of b?

So, to explain, the order of the elements in b is the indexes of the sorted elements ([3,1,2]). I would like to use that to do this:

a[[3,1,2]]
["A", "B", "C"]
like image 283
Georgery Avatar asked Aug 30 '26 19:08

Georgery


1 Answers

You are looking for sortperm:

sortperm(v; alg::Algorithm=DEFAULT_UNSTABLE, lt=isless, by=identity, rev::Bool=false, order::Ordering=Forward)

Return a permutation vector I that puts v[I] in sorted order. The order is specified using the same keywords as sort!. The permutation is guaranteed to be stable even if the sorting algorithm is unstable, meaning that indices of equal elements appear in ascending order.

Applied to your example:

julia> a = ["B", "C", "A"]
3-element Array{String,1}:
 "B"
 "C"
 "A"

julia> b = [7, 10, 5]
3-element Array{Int64,1}:
  7
 10
  5

julia> perm = sortperm(b)
3-element Array{Int64,1}:
 3
 1
 2

julia> a[perm]
3-element Array{String,1}:
 "A"
 "B"
 "C"
like image 170
François Févotte Avatar answered Sep 09 '26 22:09

François Févotte



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!