Is there a built-in binary-search In Ruby?

后端 未结 3 1489
北恋
北恋 2020-12-05 23:05

I am looking for a built-in Ruby method that has the same functionality as index but uses a binary search algorithm, and thus requires a pre-sorted array.

3条回答
  •  时光说笑
    2020-12-05 23:44

    I use bsearch. This is how it works:

    array = ['one', 'two', 'three', 'four', 'five']
    
    search = array.sort.bsearch { |value| 'four' <=> value }
    

    Note: binary search needs a sorted array; this adds a li'l overhead but it's fine, compared to the speed of the search.

    search will return the value four of the array, else nil if it doesn't find the value.

提交回复
热议问题