Modify `r`th largest entry of vector in place

Thanks for slogging through it. After further experimentation, my previous idea of a[order[3]] = 1 turns out to be correct.

The thing is, I do want to modify a, in place, using a function whose behavior depends on which “rank” of a on which it operates.

julia> a = rand(10)
10-element Array{Float64,1}:
 0.9679461796327264
 0.06561999889746284
 0.11738337626095086
 0.7960588746091037
 0.8587013475046998
 0.10976984317050542
 0.24876025355689024
 0.8062624044798408
 0.2840384536852898
 0.8210625203870776

Suppose I want to replace the smallest entry with the number 1, the second smallest with the number 64, and the eighth smallest with its logarithm.

Notice that I can do this, without copying a or doing any searching other than the original sort, as follows:

julia> order = sortperm(a)
10-element Array{Int64,1}:
  2
  6
  3
  7
  9
  4
  8
 10
  5
  1

julia> a[order[1]] = 1
1

julia> a[order[2]] = 64
64

julia> a[order[8]] = log(a[order[8]])
-0.19715602092229395

julia> a
10-element Array{Float64,1}:
  0.9679461796327264
  1.0
  0.11738337626095086
  0.7960588746091037
  0.8587013475046998
 64.0
  0.24876025355689024
  0.8062624044798408
  0.2840384536852898
 -0.19715602092229395

And the unmodified entries of a still appear in the unmodified order.

2 Likes