您可以使用返回的Enumerator
对象返回each_with_index
嵌套的[value, index]
对数组,然后对该数组进行二进制搜索:
a = [1,2,4,5,6]
new_elm = 3
index = [*a.each_with_index].bsearch{|x, _| x > new_elm}.last
=> 2
a.insert(index, new_elm)
编辑:
我已经运行了一些简单的基准测试来回答您的问题,其中包含一个长度数组1e6 - 1
:
require 'benchmark'
def binary_insert(a,e)
index = [*a.each_with_index].bsearch{|x, _| x > e}.last
a.insert(index, e)
end
a = *1..1e6
b = a.delete_at(1e5)
=> 100001
Benchmark.measure{binary_insert(a,b)}
=> #<Benchmark::Tms:0x007fd3883133d8 @label="", @real=0.37332, @cstime=0.0, @cutime=0.0, @stime=0.029999999999999805, @utime=0.240000000000002, @total=0.2700000000000018>
考虑到这一点,您可能会考虑尝试使用堆或 trie 而不是数组来存储您的值。特别是堆具有恒定的插入和删除时间复杂性,使其成为大型存储应用程序的理想选择。在此处查看这篇文章:Ruby 算法:排序、trie 和堆