使用c++标准库(vector)实现二分法查找基本算法
#include <iostream>
#include <vector>
#include <algorithm>
using namespacestd;
vector<int> numbers;
int target;
int main()
{
void input_numbers();
void display_squence();
void look_up_mid();
input_numbers();
sort(numbers.begin(),numbers.end()); /*排序*/
display_squence();
cout<<“please input the number you want to find:”<<endl;
cin>>target; /* 查找目标 */
cout<<“the target number is:”<<target<<endl;
look_up_mid(); /* 二分法查找 */
}
void input_numbers()
{
int input;
cout<<“please enter squence:”<<endl;
while(cin>>input)
{
numbers.push_back(input);
}
cin.clear(); /*刷新流*/
cin.ignore(1);
}
void display_squence()
{
auto beg=numbers.begin();
auto end=numbers.end();
cout<<“the squnece is:”<<endl;
while(beg!=end)
{
cout<<” “<<*(beg++)<<ends;
}
cout<<endl;
}
void look_up_mid()
{
auto beg=numbers.begin();
auto end=numbers.end();
auto mid=numbers.begin()+(numbers.end()-numbers.begin())/2;
while (beg!=end && *mid!=target)
{
if (target<*mid)
end=mid;
else
beg=mid+1;
mid=beg+(end-beg)/2;
}
if(*mid==target)
cout<<target<<“exits in squence!”<<endl;
else
cout<<target<<“does not exit in squence!”<<endl;
}