计算二进制搜索中的比较

时间:2018-04-13 04:58:38

标签: c# algorithm search binary

我已经完成了一项任务,我需要计算比较次数'给定的二进制搜索程序。

问题是二进制搜索使用if,else if,else语句,并且无法在这些比较之间插入计数器增量语句。

是否有适合将比较计数与测试效率保持一致的设计方法?

here上还有另一个SO问题,但答案表明计数器将以1-2的增量关闭。如果每次检查条件时进行比较,将它放在比较体中是否不准确(只有当它被评估为真时?)。

在伪代码中我有:

binarysearch(array, k)
   counter = 0;
   x = 0;
   length = array.length

  while (0 <= length)
    int middle = length + x / 2;

     counter+1; 
     if (x is array[middle]) {print(counter) return middle;}
     else if (k < array[middle]) { x = middle - 1; counter + 1; }
     else { x = middle + 1; counter + 1; }

  Print(counter);
  Return -1;

2 个答案:

答案 0 :(得分:3)

  

问题是二进制搜索使用if,else if,else语句   而且它之间不可能插入一个计数器增量语句   这些比较。

您无法计算比较的断言,因为您无法在if中增加,else ifelse是错误的。是的,它是真的,你不能总是按照你喜欢的方式在条件陈述中增加。虽然你仍然可以数数。

以实例

为例
If(some comparison)
{
   // if we get here we obviously made a comparison and it was true
   Comparisons +=1;
}
else if (some comparison)
{
   // If we get here we obviously made 2 comparisons
   // the first was false, this is true. 
   // However regardless, 2 Comparisons were made 
   Comparisons +=2;
}
else
{
   // if we get here we obviously made 2 comparisons both were false
   // however 2 comparisons were still made 
   Comparisons +=2;
}

答案 1 :(得分:1)

尝试这样的事情:

 binarysearch(array, k)
   counter = 0;
   x = 0;
   length = array.length

   while (0 <= length)
    int middle = length + x / 2;

     if ((++counter>0) and x is array[middle]) {print(counter) return middle;}
     else if ((++counter>0) and k < array[middle]) { x = middle - 1; }
     else { x = middle + 1; }

  Print(counter);
  Return -1;

(++ counter&gt; 0)始终为true,不会更改if条件