Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Ruby | Array bsearch() operation

  • Last Updated : 08 Jan, 2020

Array#bsearch() : bsearch() is an Array class method which finds a value from the array that meets with the given condition. It’s 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()

Parameter: 
- Arrays to search elements. 
- condition block

Return:  Array element that satisfy the given condition

Code #1 : Example for bsearch() method




# Ruby code for bsearch() method
   
# declaring array
a = [1, 2, 3, 4]
   
# declaring array
b = [111.11, 2.5, 4.3, 2.224]
  
# array elements that meets the condition
puts "search : #{a.bsearch {|x| x >=4 }}\n\n"
  
puts "search : #{b.bsearch {|x| x >=3 }}\n\n"
  
puts "search : #{a.bsearch {|x| x >=2 }}\n\n"
  
puts "search : #{b.bsearch {|x| x >=2 }}\n\n"

Output :

search : 4

search : 4.3

search : 2

search : 111.11

Code #2 : Example for bsearch() method




# Ruby code for bsearch() method
   
# declaring array
a = [1, 2, 3, 4]
   
# declaring array
b = [111.11, 2.5, 4.3, 2.224]
  
# array elements that meets the condition
puts "search : #{a.bsearch {|x| 1 - x / 4  }}\n\n"
  
puts "search : #{b.bsearch {|x| 2*x > 1 }}\n\n"

Output :

search : 4

search : 111.11



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!