【发布时间】:2017-07-02 01:22:42
【问题描述】:
我正在尝试编写一个函数,该函数采用整数数组并在数组的第一个和最后一个之间搜索给定值的部分。如果值在数组中,则返回该位置。如果不是,我想返回-1。
这是我的函数的代码。
int binarySearch(int *array, int min, int max, int value) {
int guess = 0;
bool found = false;
while (!found) {
guess = ((array[min] + array[max]) / 2);
if (array[guess] == value) {
found = true;
return guess;
}
else if (array[guess] < value) {
min = guess + 1;
}
else if (array[guess] > value) {
max = guess - 1;
}
}
return -1;
}
当您要搜索的值不在数组中时,我不确定如何跳出 while 循环?这是我为实现二进制搜索功能而遵循的伪代码:
- 令 min = 0 和 max = n-1(数组大小 -1)。将猜测计算为最大值和的平均值 min,向下取整(使其为整数)。
- 如果数组[猜测]等于 目标,然后停止。你找到了!返回猜测。
- 如果猜对了 低,即array[guess]
- 否则,猜测太高了。设置最大值 = 猜测 - 1。
- 返回步骤 2。
【问题讨论】:
-
递归算法通常不需要while循环。
标签: c++ function binary-search