c# - 二分查找中的比较计数

标签 c# algorithm search binary

我接到一项作业,需要计算给定二分查找程序进行的“比较次数”。

问题是二分查找使用 if、else if、else 语句,并且不可能在这些比较之间插入计数器增量语句。

是否有一种设计方法适合记录测试效率的比较?

关于这个 here 还有另一个问题但答案评论说计数器将关闭 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;

最佳答案

The problem is the Binary Search uses an if, else if, else statement and it's not possible to insert a counter increment statement between these comparisons.

您无法对比较进行计数的断言,因为您无法在 ifelse 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;
}

关于c# - 二分查找中的比较计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49809589/

相关文章:

search - 如何从 Google 搜索获取原始 PDF 文件(而不是 HTML 版本!)?

c# - 使用 MVC Controller 重载

c# - 如何判断分部方法没有实现

c# - 如何在 C# 中获取当前登录的 Visual Studio 用户的名称?

algorithm - 使用 MapReduce 对 2^32 个数字进行随机洗牌的可能性

查找数据集中元素之间关系的算法

java - 找出将 n 表示为两个有边界整数之和的方法的数量

ios - 我可以在不使用 map 的情况下在 Swift 中进行位置搜索吗?

python - 改进正则表达式以从 Google 搜索中捕获完整的电子邮件?

c# - 如何通过 LINQ to XML 创建 Dictionary<int, string>?