Application for sortperm in julia
Code
sortperm
returns an array of indices that would sort the given array1. It might sound complicated when you hear it, but looking at an example makes it immediately clear.
julia> foo = ['다', '나', '라', '가']
4-element Vector{Char}:
'다': Unicode U+B2E4 (category Lo: Letter, other)
'나': Unicode U+B098 (category Lo: Letter, other)
'라': Unicode U+B77C (category Lo: Letter, other)
'가': Unicode U+AC00 (category Lo: Letter, other)
julia> sortperm(foo)
4-element Vector{Int64}:
4
2
1
3
julia> foo[sortperm(foo)]
4-element Vector{Char}:
'가': Unicode U+AC00 (category Lo: Letter, other)
'나': Unicode U+B098 (category Lo: Letter, other)
'다': Unicode U+B2E4 (category Lo: Letter, other)
'라': Unicode U+B77C (category Lo: Letter, other)
Tricks
While not a built-in function, here’s a common trick using sortperm
.
ranking
ranking(x) = sortperm(sortperm(x, rev = true))
This returns the ranking of an array. There is a ranking function in the statistical package StatBase.jl
as well2. However, since it can be easily implemented with sortperm
, this method is often used when only ranking is needed without loading the package.
julia> a = randn(5)
5-element Vector{Float64}:
0.7795283609374186
0.6230493124556412
1.7323736283590032
-2.0790567409341945
-0.05984808360056012
julia> ranking(a)
5-element Vector{Int64}:
2
3
1
5
4
argnth
argnth(n, A) = sortperm(A, rev = true)[n]
This returns the index of the n
-th largest element. It’s tricky to implement without sortperm
.
julia> b = randn(5)
5-element Vector{Float64}:
-0.45523175238444824
0.2671034422090365
-1.0703159524443844
-0.4218688982647255
-0.27806227968448743
julia> argnth(3, b)
4
Environment
- OS: Windows
- julia: v1.10.0