输入10个数,输入想要找的数,得出其在数组中的位置。
#include <iostream>
#include <vector>
using namespace std;
/**
*@NWNU ziyif
*/
class Sloution{
public:
int BinSearch(vector<int> &nums,int target){
int pos=-1;
bool temp=false;
int low=0;
int high=nums.size()-1;
int mid;
while(!temp&&low<=high){
mid=(low+high)/2;
if(target>nums[mid]){
low=mid+1;
}
else if(target<nums[mid]){
low=mid-1;
}
else{
pos=mid;
temp=true;
}
}
return pos;
}
};
int main()
{
Sloution s;
vector<int>v1;
cout<<"v1=";
int num;
for(int i=0;i<10;i++){
cin>>num;
v1.push_back(num);
}
int target;
cout<<"target=";
cin>>target;
int pos=s.BinSearch(v1,target);
if(pos<0){
cout<<"Not Found"<<endl;
}
else{
cout<<"pos="<<pos<<endl;
}
return 0;
}
|