我只想知道这段代码中的问题是什么;我从youtube上得到的,但问题是当我传递x的值时。它什么也没做,只显示空白屏幕。
#include <iostream>
#include <algorithm>
using namespace std;
// use binary search
int find(int arr[], int n, int x, bool leftmost){
int low = 0;
int high = n-1;
int mid = low + (high - low)/2;
int res = -1;
while (low <= high){
if (arr[mid] == x){
res = mid;
if (leftmost){ // it flag is true we will find the left most
high = mid - 1;
}else{ //else we will find the right most
low = mid+1;
}
}
if (arr[mid] > x){
high = mid - 1;
}
else{
low = mid +1;
}
}
return res;
}
int main() {
int arr[] = {2,2,3,3,3,3};
int n = sizeof(arr) / sizeof(arr[0]);
int x;
cout << "Enter the number "<< endl;
cin >> x;
int leftidx = find(arr, n, x, true);
int rightidx = find(arr, n, x, false);
cout << (rightidx - leftidx) +1;
return 0;
}
在其他几个程序中出现此问题。所以,如果你有时间,帮我。感谢
您没有更新mid
变量,因此循环将无限。将此添加到循环的末尾:
/...
else{
low = mid +1;
}
mid = (low + high) / 2; // add this line
也要保持简单,下面的代码:
int mid = low + (high - low)/2;
相当于:
int mid = (low + high)/2;
//or just
int mid = high / 2;
不要给代码增加不必要的复杂性。