Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using bsearch to find index for inserting new element into sorted array

Tags:

ruby

bsearch

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?

like image 409
Jonah Avatar asked May 05 '14 20:05

Jonah


People also ask

How do you find the index of an element in an array using binary search?

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.

How do you add an element to an array in binary search?

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.


1 Answers

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)
like image 125
eXa Avatar answered Sep 21 '22 22:09

eXa