如何在C++中为二进制搜索设置计数器
How to have a counter for a binary search in C++?
我不知道如何为二进制搜索设置计数器,以确定在找到输入的目标数字之前进行了多少比较。我是否在二进制搜索的末尾添加一个计数器?
void search (int arr[])
{
int target;
int first = 0,
last = MAX - 1,
mid,
position = -1;
int row = 2;
bool found = false;
cout << "Enter in target number to search for: ";
cin >> target;
while (!found && first <= last)
{
mid = (first + last) / 2;
if (avg[row][mid] == target)
{
cout << "found at index " << mid << endl;
found = true;
}
else if (avg[row][mid] > target)
last = mid - 1;
else
first = mid + 1;
}
if (!found)
cout << "Not foundn";
}
int counter = 0; // Number of comparisons before target is found
while (!found && first <= last)
{
mid = (first + last) / 2;
counter = counter + 1; // Changes to be made
... Rest of the code
else
first = mid + 1;
}
或
int counter = 0; // Number of comparison before target is found
while (!found && first <= last)
{
mid = (first + last) / 2;
if (avg[row][mid] == target)
{
cout << "found at index " << mid << endl;
found = true;
counter = counter + 1;
}
else if (avg[row][mid] > target)
{
last = mid - 1;
counter = counter + 1; // Changes to be made
}
else
{
first = mid + 1;
counter = counter + 1; // Changes to be made
}
}
这里,计数器在while循环之前声明,然后每次递增一,直到找到结果。
我会在while循环之前定义一个计数器变量,并在while环路结束时,在最后一个else(不在else子句中)
int计数=0;…代码的其余部分否则if(avg[row][mid]>目标)last=mid-1;计数++
else
first = mid + 1;
count++;
}if(!已找到)cout<lt;"未找到\n";cout<lt;"counter="<
相关文章:
- 有根的二进制搜索树.保留与其父级的链接
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- 二进制搜索树叶数问题
- 为什么二进制搜索在我的测试中不起作用
- 正在尝试重载二进制搜索树分配运算符
- 我的二进制搜索程序只是关闭了
- 二进制搜索的终止点
- 递归二进制搜索与字符串数组
- 测试树是否为二进制搜索树
- 如何二进制搜索结构向量并在适当的索引处插入
- 如果你有一个固定大小的数组,你需要遍历它!n次,使用二进制搜索如何改变时间复杂性
- 字符串的递归二进制搜索-C++
- 使用二进制搜索树中的迭代器对象访问左侧节点
- 二进制搜索树没有匹配的函数调用
- 二进制搜索不适用于特定输出
- 如何在向量上进行二进制搜索以找到具有特定id的元素
- 二进制搜索树不变的标头文件
- 二进制搜索树插入带参数参考
- 二进制搜索不变以查找元素的首次出现
- 了解一种神秘地起作用的递归二进制搜索算法