飘云阁

 找回密码
 加入我们

QQ登录

只需一步,快速开始

查看: 2302|回复: 8

[C/C++] 发段忽悠人的二分法查找代码

[复制链接]

该用户从未签到

发表于 2009-8-30 21:03:18 | 显示全部楼层 |阅读模式
#include <iOStream>
using namespace std;

int test[]={1,2,3,4,5,6,7,8,9,10};

bool Find(int nFirst,int nEnd,int nFind)
{
    if(nFirst == nEnd) return test[nFirst]==nFind;
    int nLeft=(nFirst+nEnd)/2;
    return (test[nLeft]>=nFind && Find(nFirst,nLeft,nFind)) ||
        (test[nLeft+1]<=nFind && Find(nLeft+1,nEnd,nFind));
}

int main(int argc, char* argv[])
{
    cout<<"膜拜下小齐~@!"<<endl;
    Find(0,9,9)==1?cout<<"找到了"<<endl:cout<<"没找到"<<endl;
    return 0;
}
PYG19周年生日快乐!
  • TA的每日心情
    开心
    2022-11-16 14:28
  • 签到天数: 5 天

    [LV.2]偶尔看看I

    发表于 2009-8-30 21:24:44 | 显示全部楼层
    /:L .......又BS我!......
    PYG19周年生日快乐!

    该用户从未签到

    发表于 2009-8-30 21:27:30 | 显示全部楼层
    写的好简单阿,一看到递归就头晕/:L
    PYG19周年生日快乐!

    该用户从未签到

    发表于 2009-8-30 21:31:28 | 显示全部楼层
    很强大啊
    PYG19周年生日快乐!

    该用户从未签到

     楼主| 发表于 2009-8-30 22:33:31 | 显示全部楼层
    其实把代码写成这样根本就没有意义 就跟那个汉诺塔一样

    #include <iostream>
    using namespace std;

    void mov(int n,char a,char b,char c)
    {
        if(n==0)return;
        mov(n-1,a,c,b);
        cout<<a<<"-->"<<c<<endl;
        mov(n-1,b,a,c);
    }

    int main(int argc, char* argv[])
    {
        mov(3,'a','b','c');
        return 0;
    }

    告诉别人汉诺塔这样写 其实没啥意义

    bool Find(int nFirst,int nEnd,int nFind)
    {

        if(nFirst == nEnd) return test[nFirst]==nFind?1:0;
        if(test[nFirst]==nFind || test[nEnd]==nFind) return true; // 这里属于优化代码 省略
        int nLeft=(nFirst+nEnd)/2;
        if(test[nLeft]>=nFind)               // 将一下两组if指令用老师教的&&来等价替换
            if(Find(nFirst,nLeft,nFind))
                return true;
        if(test[nLeft+1]<=nFind)
            if(Find(nLeft+1,nEnd,nFind))
                return true;
        return false;
    }

    重要是递归的思想、本质 和 递归的建模你是否搞明白了 这才是核心
    PYG19周年生日快乐!

    该用户从未签到

    发表于 2009-9-1 15:53:54 | 显示全部楼层
    嗯嗯,老秦命名包准了好多/:023
    PYG19周年生日快乐!
  • TA的每日心情
    开心
    2022-11-16 14:28
  • 签到天数: 5 天

    [LV.2]偶尔看看I

    发表于 2009-9-1 16:41:30 | 显示全部楼层
    /:QQ2 人家当初是支初国语呀!
    PYG19周年生日快乐!

    该用户从未签到

     楼主| 发表于 2009-9-1 21:25:32 | 显示全部楼层
    向小齐命名法看齐 ~~
    PYG19周年生日快乐!
  • TA的每日心情
    开心
    2022-11-16 14:28
  • 签到天数: 5 天

    [LV.2]偶尔看看I

    发表于 2009-9-1 21:30:15 | 显示全部楼层
    别,我的命名很烂的,编程风格超超的非常之不错!
    PYG19周年生日快乐!
    您需要登录后才可以回帖 登录 | 加入我们

    本版积分规则

    快速回复 返回顶部 返回列表