【发布时间】:2020-03-13 20:41:11
【问题描述】:
所以.. 我已经了解了二进制搜索及其工作原理,甚至尝试使用常量数组而不需要用户的任何输入,但现在我尝试应用向量而不是数组来让用户输入两者的值从 vector 中搜索数字的列表和要搜索的目标。这里我在使用数组时使用了普通的分治法
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;
}
我的问题是我使用向量做了几乎相同的方法,但它显示了无限数量的 **Your result is found at the index: ** (number of wrong index) 。或者根本不显示任何结果,甚至显示未找到结果,每次都以某种方式不同。这是在使用向量时
#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;这部分,也许是关于如何使用向量的大小?有人可以启发我吗
【问题讨论】:
-
您是否考虑过您的阵列版本总是损坏,并且使用
vector检测到损坏?其次,为什么不将数据硬编码到向量中并进行测试,就像在数组版本中一样? -
请注意,二分查找仅适用于已排序的数据集。如果用户输入未排序的数据,那么您需要先对向量进行排序,然后才能对其进行二进制搜索。
-
好点,谢谢! NathanOliver 我不明白你所说的总是坏是什么意思,你能解释一下@PaulMcKenzie
-
有时使用数组会隐藏一个个或其他细微的错误。使用向量时,程序的行为可能会有所不同,此时隐藏的错误就会暴露出来。