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
相關用法
- Ruby Array map!()用法及代碼示例
- Ruby Array dig()用法及代碼示例
- Ruby Array any?()用法及代碼示例
- Ruby Array at()用法及代碼示例
- Ruby Array cycle()用法及代碼示例
- Ruby Array delete()用法及代碼示例
- Ruby Array combination()用法及代碼示例
- Ruby Array drop()用法及代碼示例
- Ruby Array collect()用法及代碼示例
- Ruby Array collect!()用法及代碼示例
- Ruby Array clear()用法及代碼示例
- Ruby Array bsearch_index()用法及代碼示例
- Ruby Array rassoc()用法及代碼示例
- Ruby Array class each()用法及代碼示例
- Ruby Array class eql?()用法及代碼示例
注:本文由純淨天空篩選整理自mayank5326大神的英文原創作品 Ruby | Array bsearch() operation。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。