Hi, I’m trying to find the index of the two largest values in an array.
I’ve been trying to work through find n smallest values in an n dims array but am getting confused because that is a 3D array.
This probably has a simple solution but it is evading me. I can’t use findmax() or argmax() since I don’t just want the largest value.
Edit: @DNF’s suggestion is to use partialsortperm … which is for sure better in this case. @fatteneder’s answer is apparently faster, and allocates less.
EDIT: Updated to return the indices of the two largest values and not their values.
If linear complexity is desired then just use a loop, because they are also fast in Julia:
function findlargest2(a::AbstractVector)
@assert length(a) >= 2
i1, i2 = 1, 2
max1, max2 = a[i1], a[i2]
if max1 < max2
max1, max2 = max2, max1
end
for i = 3:length(a)
ai = a[i]
if ai > max2
if ai > max1
i1, i2 = i, i1
max1, max2 = ai, max1
else
i2 = i
max2 = ai
end
end
end
return i1, i2
end
It works, so thank you!. Why is rev = true (reverse sorting is performed)? If I make it false, the answer doesn’t make sense. Say the answer with rev = true is 4,2. I would expect the answer when rev = false to be 2,4 but the answer is 6, 5.