Ruby | Array bsearch_index() operation
Array#bsearch_index() : bsearch_index() is an Array class method which finds the index of the array value that meets with the given condition. Its complexity is O(log n) where n is the array size. This method can work in both the modes – find-minimum and find-any mode.
Syntax: Array.bsearch_index() Parameter: - Arrays to search elements. - condition block Return: Index value of the array element that satisfy the given condition
Code #1 : Example for bsearch_index() method
# Ruby code for bsearch_index() method # declaring array a = [ 1 , 2 , 3 , 4 ] # declaring array b = [ 111 . 11 , 2 . 5 , 4 . 3 , 2 . 224 ] # array that meets the condition puts "search : #{a.bsearch_index {|x| x >=4 }}\n\n" puts "search : #{b.bsearch_index {|x| x >=3 }}\n\n" puts "search : #{a.bsearch_index {|x| x >=2 }}\n\n" puts "search : #{b.bsearch_index {|x| x >=2 }}\n\n" |
Output :
search : 3 search : 2 search : 1 search : 0
Code #2 : Example for bsearch_index() method
# Ruby code for bsearch_index() method # declaring array a = [ 1 , 2 , 3 , 4 ] # declaring array b = [ 111 . 11 , 2 . 5 , 4 . 3 , 2 . 224 ] # array that meets the condition puts "search : #{a.bsearch_index {|x| 1 - x / 4 }}\n\n" puts "search : #{b.bsearch_index {|x| 2*x > 1 }}\n\n" |
Output :
search : 3 search : 0
Please Login to comment...