给定序列:1 ,3 ,6 ,9, 17 ,31 ,39 ,52 ,61 ,79 ,81 ,90 ,96 。使⽤以下代码进⾏⼆分查找查找元素82时 ,需要循环多少次, 即最后输出的times值为( ) 。
1 int binarySearch(const std::vector<int>& arr, int target) { 2 int left = 0; 3 int right = arr.size() - 1; 4 int times = 0; 5 while (left <= right) { 6 times ++; 7 int mid = left + (right - left) / 2; 8 if (arr[mid] == target) { 9 cout << times << endl; 10 return mid; 11 } else if (arr[mid] < target) { 12 left = mid + 1; 13 } else { 14 right = mid - 1; 15 } 16 } 17 cout << times << endl; 18 return -1; 19 }
2
5
3
4