我想写一个函数,它需要一个整数数组&在给定值的第一个和最后一个之间搜索数组部分。如果该值在数组中,则返回该位置。如果不是,我想返回-1。二进制搜索算法C++
这里是我的功能代码。
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)。计算最大值和最小值的平均值,向下舍入(使其为整数)。
- 如果array [guess]等于 target,则停止。你找到了!返回猜测。
- 如果猜测是太 低,即,阵列[猜测] <目标,则设置最低=猜测+ 1
- 否则,猜测是太高了。设置最大=猜测 - 1
- 回到步骤2
递归算法通常不需要while循环。 –