当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Ruby Array bsearch()用法及代码示例


Array#bsearch():bsearch()是一种Array类方法,该方法从满足给定条件的数组中查找一个值。它的复杂度为O(log n),其中n是数组大小。此方法可以同时在两种模式下工作-find-minimum和find-any模式。

用法: Array.bsearch()

参数: 
- Arrays to search elements. 
- condition block

返回: Array element that satisfy the given condition

代码#1:bsearch()方法示例

# 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"

输出:


search:4

search:4.3

search:2

search:111.11

代码2:bsearch()方法示例

# 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"

输出:

search:4

search:111.11


相关用法


注:本文由纯净天空筛选整理自mayank5326大神的英文原创作品 Ruby | Array bsearch() operation。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。