I want to insert a value into a sorted array with fixed size, removing the last (greatest) value of the array. A naive solution is this function that combines insert!
(or pushfirst!
) and pop!
:
function insertandropgreatest_naive!(collection, newvalue)
if newvalue >= last(collection)
return collection
end
i = searchsortedlast(collection, newvalue)
if i==0
pushfirst!(collection, newvalue)
else
insert!(collection, i, newvalue)
end
pop!(collection)
return collection
end
I thought that it would be better to make something that does not redimension the array, like this:
function insertandropgreatest_fixedsize!(collection, newvalue)
# do nothing if newvalue is greater than greatest in collection
if newvalue >= last(collection)
return collection
end
# search, and replace...
for i = length(collection):-1:2
collection[i] = collection[i-1]
if newvalue >= collection[i]
collection[i] = newvalue
return collection
end
end
# replace in first position if newvalue is smaller than smallest in collection
collection[1] = newvalue
return collection
end
An advantage of this is that it works with MArrays
(from StaticArrays.jl), but for standard arrays I can’t see a big gain in performance. Is the “naive” version sufficiently optimized for this problem, or does anyone have some suggestion to improve it?
NB: I’m starting the search from the greatest to the smallest, because I expect newvalue
to be greater than all elements of collection
more frequently.