所以...我已经学习了二分查找以及它的工作原理,并尝试在没有用户输入的情况下使用常量数组进行操作,但现在我正在尝试使用向量而不是数组来让用户输入要从中搜索数字的列表,以及要搜索的目标。在这里,我使用了普通的分治算法来处理数组。
using namespace std;
int Binary_search(int x[],int size,int target){
int maximum= size-1;
int minimum = 0;
int mean;
while (maximum>minimum){
mean = (maximum+minimum)/2;
if (x[mean] == target){
cout << "The number you're looking for is found! \n";
return mean;
}
else if(x[mean] > target){
maximum = (mean-1);
}
else{
minimum = (mean+1);
}
}
return -1;
}
int main(){
int x[]={1,2,3,4,5};
int a=sizeof(x)/sizeof(x[0]);
int target=4;
int show=Binary_search(x,a,target);
if (show != -1){
cout << "Your result is in the index: " << show;
}
return 0;
}
我的问题是,我用vector编写了几乎相同的方法,但它要么显示出无限数量的“您的结果位于索引:”(错误索引数),要么根本不显示任何结果,甚至显示未找到结果,每次都有所不同。以下是使用vector时的代码:
#include <iostream>
#include <vector>
using namespace std;
int Binary_search(vector<int>x,int target){
int maximum=(x.size())-1;
int minimum = 0;
int mean;
while (maximum>minimum){
mean = (maximum+minimum)/2;
if (x[mean] == target){
cout << "The number you're looking for is found! \n";
}
else if(x[mean] > target){
maximum = (mean-1);
}
else{
minimum = (mean+1);
}
}
return -1;
}
int main(){
unsigned int i;
int n;
vector<int>x;
cout << "Enter the amount of numbers you want to evaluate: ";
cin >> i;
cout << "Enter your numbers to be evaluated: " << endl;
while (x.size() < i && cin >> n){
x.push_back(n);
}
int target;
cout << "Enter the target you want to search for in the selected array \n";
cin >> target;
int show = Binary_search(x,target);
if (show == -1){
cout << "Your result is not found ! ";
}
else{
cout << "Your result is in the index: " << show;
}
return 0;
}
我认为问题出在这部分代码 int maximum=(x.size())-1;
,也许与如何使用向量的大小有关?能否有人给我解惑一下?