Description
实现二分查找函数,函数接口如下。
/* size为数组s的实际大小。
假定s非递减有序,如果s中存在值为target的元素,
则返回最后一次出现的位序号,否则返回-1表示不存在。
位序号从0开始计。*/
int binSearch(const int s[], const int size, const int target)
{
// 请将实现代码添加在这里
}
提交时只需提交上述函数,不要提交main()函数。
调用例子:
int s[8] = {0,1,1,3,3,3,6,6};
cout << binSearch(s,8,3) << endl; //输出5
cout << binSearch(s,8,4) << endl; //输出-1
Hint
不允许使用STL库里面的相关函数和库(否则可能会出现编译错误)
包括iostream, map, vector, set, algorithm, queue等
这次是简单的二分查找,只需要完成其中一个函数就行了,要注意的地方就是最后需要进行一下移位,保证有多个相同的时候,下标是最大的
int binSearch(const int s[], const int size, const int target) {
int low = 0, high = size, mid;
bool flag = false;
while (low <= high) {
mid = (low + high)/2;
if (target < s[mid]) high = mid - 1;
else if (target > s[mid]) low = mid + 1;
else {flag = true; break;}
}
if (flag == true) { // have find the target
while (s[mid] == target) {mid++;}
return mid;
}
else return -1;
}