码迷,mamicode.com
首页 > 其他好文 > 详细

二分法习题讲解

时间:2014-07-18 14:24:25      阅读:314      评论:0      收藏:0      [点我收藏+]

标签:使用   os   io   re   c   ios   

#include <iostream>
using namespace std;
int num[]={3,5,7,9,10,12,15,20,25,30};//10个数
int main()
{
int x;
while(cin>>x)
{
int L,R,mid;
L=0;R=9;
while(L<R) //找到x值的位置
{
//使用该方法的原因是如果存在负数的一些情况,可以实现真正的找到中间值的效果,当然,实际使用情况值得考究
mid=L+(R-L)/2;
//mid=(L+R)/2
if (num[mid]>=x) R=mid; //?
else L=mid+1;//现在就应该注意这个加1的效果了,如果没有,可能最后会陷入一个死循环
}
if (num[L]==x){
cout<<"The x is find in "<<L<<endl;//最后应该是左边的指针指向目标值,否则就算是失败
}
else
cout<<"No find"<<endl;

//第二种写法:
int ans=-1;
L=0;R=9;
while(L <= R){
mid = (L+R)/2;
if(num[mid] == x){
ans = mid;
break;
}else(num[mid] > x){
R = mid-1;
}else
L = mid+1;
}

}
}

//当在使用第二种方法是不容易陷入死循环中

二分法习题讲解,布布扣,bubuko.com

二分法习题讲解

标签:使用   os   io   re   c   ios   

原文地址:http://www.cnblogs.com/tianxia2s/p/3852730.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!