CircularBuffer//insert value

If you actually need to maintain a sorted list between insertions I’m not sure that a CircularBuffer is going to help and you probably won’t do much better than just maintaining a sorted vector

function push_with_cap!(v, item, cap)
  ii = searchsortedlast(v, item; rev=true)
  insert!(v, ii+1, item)
  while length(v) > cap
    pop!(v)
  end
end

buf = Float64[]
sizehint!(buf, capacity+1)
append!(buf, 1.0:5.0)
sort!(buf; rev=true)

push_with_cap!(buf, 3.5, 5)

Since it is more efficient to add and remove from the end of a vector we maintain it in reverse order.

HTH

1 Like