Get index of array element faster than O(n)

前端 未结 8 1323
春和景丽
春和景丽 2020-12-07 09:28

Given I have a HUGE array, and a value from it. I want to get index of the value in array. Is there any other way, rather then call Array#index to get it? The p

8条回答
  •  温柔的废话
    2020-12-07 10:19

    If it's a sorted array you could use a Binary search algorithm (O(log n)). For example, extending the Array-class with this functionality:

    class Array
      def b_search(e, l = 0, u = length - 1)
        return if lower_index > upper_index
    
        midpoint_index = (lower_index + upper_index) / 2
        return midpoint_index if self[midpoint_index] == value
    
        if value < self[midpoint_index]
          b_search(value, lower_index, upper_index - 1)
        else
          b_search(value, lower_index + 1, upper_index)
        end
      end
    end
    

提交回复
热议问题