c - 二进制搜索算法的每次迭代是否可以只进行一次比较?

标签 c algorithm optimization micro-optimization

在二分查找算法中我们有两个比较:

if (key == a[mid]) then found;

else if (key < a[mid]) then binary_search(a[],left,mid-1);
      else binary_search(a[],mid+1,right);

有没有一种方法可以让我只比较一个而不是上面两个。

--

谢谢

Alok.Kr。

最佳答案

参见:

http://en.wikipedia.org/wiki/Binary_search_algorithm#Single_comparison_per_iteration

摘自维基:

   low = 0
   high = N
   while (low < high) {
       mid = low + ((high - low) / 2)
       if (A[mid] < value)
           low = mid + 1;
       else
            //can't be high = mid-1: here A[mid] >= value,
            //so high can't be < mid if A[mid] == value
            high = mid;
   }
   // high == low, using high or low depends on taste
   if ((low < N) && (A[low] == value))
       return low // found
   else
       return -1 // not found

来自 wiki 的优点/缺点: “这种方法放弃了在发现匹配项时提前终止的可能性,因此成功的搜索有 log2(N) 次迭代而不是预期的 log2(N) − 1 次迭代。另一方面,这种实现减少了比较:log2(N ) 小于 1·5(log2(N) − 1) 的双重测试实现的预期比较次数,因为 N 大于 8。”

关于c - 二进制搜索算法的每次迭代是否可以只进行一次比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3500167/

相关文章:

c - C 中没有索引的数组的引用

xcode - 从大小为 N 的数组中选择 K 个元素,使得子数组中的最小元素和最大元素之间的差异最小

algorithm - 将循环图缩减为树(依赖图-->树)

c++ - 我是否需要针对不同的指令集制作多个可执行文件?

c++ - 优化 C++ 中的大整数减法

iphone - 如何优化我的 Controller 以使其加载速度更快?

c - 8 Queens puzzle with recursive deep search

c - for 无增量 vs while

无法从另一个文件中的函数创建线程

algorithm - Big Oh 分析结果