This method is just taking an element and inserting it in an ordered position in an already ordered array.
@ary = [9,7,3,1]
insert_in_order(5)
@ary = [9,7,5,3,1]
I’ve already determined that this is faster than just pushing the value on the array and running a sort! on it later. But it seems like this is taking way more steps than it should. Is there a more performant and more efficient way to do this?
def insert_in_order val
@val = val
@ary.each_with_index{|v,i|
if @val > v
@found_index = i
break
end
}
@found_index ? @ary.insert(@found_index, @val) : @ary.push(@val)
end
Do a binary search and find the index to which this element belongs and then insert at that index. Finding the index would take O(log(n)) and works only if the current list is guaranteed to be sorted