给定序列:$1, 3, 6, 9, 17, 31, 39, 52, 61, 79, 81, 90, 96$。使用以下代码进行二分查找查找元素 $82$ 时,需要循环多少次,即最后输出的 times 值为( )。
int binarySearch(const std::vector<int>& arr, int target) {
int left = 0;
int right = arr.size() - 1;
int times = 0;
while (left <= right) {
times++;
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
cout << times << endl;
return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
cout << times << endl;
return -1;
}STL 容器:vector(动态数组)、set/map(红黑树,有序)、unordered_set/map(哈希表,无序)。注意迭代器失效问题。
审题时注意题目要求(选正确还是选错误),避免因审题不清失分。涉及代码的题目要逐行分析变量变化。
【考点】二分查找|循环控制|边界条件
GESP 五级算法基础模块。二分查找是必考内容,但命题人卡住绝大多数考生的"过程模拟能力"——只会背对数复杂度,却数不清具体循环次数。