Get index of array element faster than O(n)

前端 未结 8 1318
春和景丽
春和景丽 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:12

    If your array has a natural order use binary search.

    Use binary search.

    Binary search has O(log n) access time.

    Here are the steps on how to use binary search,

    • What is the ordering of you array? For example, is it sorted by name?
    • Use bsearch to find elements or indices

    Code example

    # assume array is sorted by name!
    
    array.bsearch { |each| "Jamie" <=> each.name } # returns element
    (0..array.size).bsearch { |n| "Jamie" <=> array[n].name } # returns index
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题