I have a sorted unique array and want to efficiently insert an element into it that is not in the array like this:
a = [1,2,4,5,6]
new_elm = 3
insert_at = a.bsearch_index {|x| x > new_elm } # => 2
a.insert(insert_at, new_elm) # now a = [1,2,3,4,5,6]
The method bsearch_index
doesn't exist: only bsearch
, which returns the matching element rather than the matching element's index. Is there any built in way to accomplish this?
Step-by-step Binary Search Algorithm: We basically ignore half of the elements just after one comparison. Compare x with the middle element. If x matches with the middle element, we return the mid index. Else If x is greater than the mid element, then x can only lie in the right half subarray after the mid element.
Approach to implement Binary Insertion sort:Iterate the array from the second element to the last element. Store the current element A[i] in a variable key. Find the position of the element just greater than A[i] in the subarray from A[0] to A[i-1] using binary search. Say this element is at index pos.
Ruby 2.3.1 introduced bsearch_index thus the question can now be resolved this way:
a = [1,2,4,5,6]
new_elm = 3
index = a.bsearch_index{|x, _| x > new_elm}
=> 2
a.insert(index, new_elm)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With