Julia Questions: Find n-smallest value's index in vector

Viewed 168

I have two distance vector which is distance and distance_1norm and i try to get 5 of the smallest distance from those 2 vectors and compare them whether are the same.

etc

distance = [ 1, 5, 6, 7, 8, 9, 10, 2, 3, 4]

distance_1norm = [1, 8, 6, 7, 8, 9, 10, 2, 3, 4]

after sorted (I only can do until here)

distance = [1,2,3,4,5] ,distance_1norm= [1,2,3,4,6]

How can i get their index which is

distance = 1st, 8th, 9th, 10th, 2nd ,distance_1norm = 1st, 8th, 9th, 10th, 3rd

function smallestn(distance, n)
    sort(distance; alg=Sort.PartialQuickSort(n))[1:n]
end
1 Answers

Use partialsortperm:

julia> partialsortperm([1, 5, 6, 7, 8, 9, 10, 2, 3, 4], 1:5)
5-element view(::Vector{Int64}, 1:5) with eltype Int64:
  1
  8
  9
 10
  2

julia> partialsortperm([1, 8, 6, 7, 8, 9, 10, 2, 3, 4], 1:5)
5-element view(::Vector{Int64}, 1:5) with eltype Int64:
  1
  8
  9
 10
  3
Related