當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。