zoukankan      html  css  js  c++  java
  • 找数字(递归,二分查找)

    题目:在一从大到小排序的序列中用递归找一个数在不在这序列,在输出yes,不在输出no

    这题用了二分查找的递归实现

    思路:

    把数组和变量都变成全局变量方便递归函数修改

    然后如果不可能就跳出循环

    如果可能但现在没找到就缩小范围进入下一个递归过程

    如果找到了就输出

    代码:

    #include<bits/stdc++.h>
    using namespace std;
    int a[1000];
    int n,key;
    
    int finder(int l,int r)//左和右
    {
        if(l>r)
        {
            cout<<"no"<<endl;
            return 0;
        }
        int mid=(l+r)/2;
        if(a[mid]<key)
        {
            finder(l,mid-1);
    
        }
        else if(a[mid]>key)
        {
            finder(mid+1,r);
    
        }
        else
        {
            cout<<"yes"<<endl;
            return 0;
        }
    
    }
    int main()
    {
        std::ios::sync_with_stdio(false);
        cin>>n>>key;
        for(int i=1;i<=n;i++)
            cin>>a[i];
        finder(1,n);
        return 0;
    }
  • 相关阅读:
    config https in nginx(free)
    js hex string to unicode string
    alter character set
    es6
    音乐播放器
    JS模块化-requireJS
    PHP中的封装和继承
    JavaScriptOOP
    mui框架移动开发初体验
    走进AngularJS
  • 原文地址:https://www.cnblogs.com/zyacmer/p/10046973.html
Copyright © 2011-2022 走看看