global

def replace_next_larger(enum, value, last_index = nil)

This operation preserves the sort order.

are numeric.
at that point with +value+. It is assumed that the Enumerable's values
of the Enumerable), add it to the end. Otherwise, replace the element
and return +nil+. If the place does not exist (i.e., it is off the end
Enumerable. If that place is already occupied by +value+, do nothing
Find the place at which +value+ would normally be inserted into the
def replace_next_larger(enum, value, last_index = nil)
  # Off the end?
  if enum.empty? or (value > enum[-1])
    enum << value
    return enum.size - 1
  end
  # Binary search for the insertion point
  last_index ||= enum.size - 1
  first_index = 0
  while first_index <= last_index
    i = (first_index + last_index) >> 1
    found = enum[i]
    return nil if value == found
    if value > found
      first_index = i + 1
    else
      last_index = i - 1
    end
  end
  # The insertion point is in first_index; overwrite the next larger
  # value.
  enum[first_index] = value
  first_index
end