Binary search with hint

后端 未结 1 1482
攒了一身酷
攒了一身酷 2021-02-05 08:40

I have a simple std::vector containing some numbers, which are sorted (in ascending order). I want to lookup an element, so far I use:



        
1条回答
  •  孤街浪徒
    2021-02-05 09:01

    I think the algorithm you're looking for is called interpolation search which is a variation on binary search that, instead of looking at the midpoint of the array, linearly interpolates between the array endpoints to guess where the key should be. On data that's structured the way that yours is, the expected runtime is O(log log n), exponentially faster than a standard binary search.

    There is no standard implementation of this algorithm in C++, but (as a totally shameless plug) I happened to have coded this one up in C++. My implementation is available online if you're interested in seeing how it works.

    Hope this helps!

    0 讨论(0)
提交回复
热议问题