二分法(Bisection method),即一分为二的的方法。对于在区间[a,b]上连续不断且满足f(a)*f(b)<0的函数y=f(x),通过不断地把函数f(x)的零点所在区间二等分,使区间两个端点逐步逼近零点,进而得到零点的近似值的方法。
思想是把答案所在的区间逐渐缩小,直到区间内只有答案。
#include<iostream>
#include<vector>
using namespace std;
class Bisection
{
public:
vector<int> arr;
Bisection(string name);
int find_value(int value);
};
Bisection::Bisection(string name)
{
cout<<"create by"<<name<<"\n";
}
int Bisection::find_value(int value)
{
int right=arr.size();
int left=0;
while (left<right)
{
int middle=(right+left)/2;
if(arr[middle]<value)
{
left=middle;
}
else if (arr[middle]==value)
{
cout<<middle<<"\n";
break;
}
else
{
right=middle;
}
}
}
int main(){
Bisection bisection("wzw");
bisection.arr={1,2,3,4,5,6};
bisection.find_value(6);
}