红宝石 |数组 bsearch() 操作
Array#bsearch() : bsearch()是一个 Array 类方法,它从数组中找到满足给定条件的值。它的复杂度是 O(log n),其中 n 是数组大小。此方法可以在两种模式下工作——find-minimum 和 find-any 模式。
Syntax: Array.bsearch()
Parameter:
- Arrays to search elements.
- condition block
Return: 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