二分法查找

基本思路
(1)首先,从数组的中间元素开始搜索,如果该元素正好是目标元素,则搜索过程结束,否则执行下一步。

(2)如果目标元素大于/小于中间元素,则在数组大于/小于中间元素的那一半区域查找,然后重复步骤(1)的操作。

(3)如果某一步数组为空,则表示找不到目标元素。

(二分法查找的时间复杂度O(logn)。)
代码模型

int mid,r,l;
	l=1;r=n;
	while(l<r){
		mid=(l+r)/2;
		if(a[mid]==x)  breakelse if(a[mid]>x)   r=mid;
		else l=mid+1;
	}

例题

Now,given the equation 8x^4 + 7x^3 + 2x^2 + 3x + 6 == Y,can you find its solution between 0 and 100;
Now please try your lucky.
Input
The first line of the input contains an integer T(1<=T<=100) which means the number of test cases. Then T lines follow, each line has a real number Y (fabs(Y) <= 1e10);
Output
For each test case, you should just output one real number(accurate up to 4 decimal places),which is the solution of the equation,or “No solution!”,if there is no solution for the equation between 0 and 100.
Sample Input
2
100
-4
Sample Output
1.6152
No solution!

#include<iostream>
#define ee (1e-8)
double fff(double x){
	return (8*x*x*x*x+7*x*x*x+2*x*x+3*x+6);
} 
int main()
{
	int n,k;
	double mid,l,r,q;
    scanf("%d",&n);
    while(n--){
    	scanf("%lf",&q);
    	r=100;
    	l=0;
    	if(q>fff(r)||q<fff(l)){
    		printf("No solution!\n");
		}
		else {
			while(l+ee<r){
				mid=(r+l)/2.0;
				if(q>fff(mid)+ee) l=mid;
				else if(q<fff(mid)-ee) r=mid;
				else break;
			}
			printf("%.4lf\n",mid);
		}
	}
}
posted @ 2021-01-22 21:42  HN_N  阅读(50)  评论(0)    收藏  举报