Java函数递归—1+1+···+1(10个1相加)、斐波那契数、阶乘、二分查找

目录

函数递归条件

例子

1+1+1······+1(10个1相加)

阶乘 4!=4*3*2*1=24

斐波那契数 

二分查找递归算法


函数递归条件

函数递归使用的条件是:1)自己调自己  2)问题规模不断缩小 3)有函数出口

例子

以下用例子来说明:

1+1+1······+1(10个1相加)

public class testDome {
    public static int getSum(int n) {
        if(n == 1){
            return 1;
        }
        return getSum(n-1)+1;
    }
    public static void main(String[] args){
        System.out.println(getSum(10));
    }
}

阶乘 4!=4*3*2*1=24

public class testDome {
    public static int getRide(int n) {
        if (n == 0){
            return 0;
        }else if(n == 1){
            return 1;
        }else {
            return n * getRide(n - 1);
        }
    }
    public static void main(String[] args){
        System.out.println(getRide(4));
    }


}

斐波那契数 

打印第10个数

public class testDome {
    public static int Fibonacci(int n) {
        if(n == 1||n == 2){
            return  1;
        }else {
            return Fibonacci(n-1)+ Fibonacci(n-2);
        }
    }
    public static void main(String[] args){
        System.out.println(Fibonacci(10)); // 55
    }
}

二分查找递归算法

public class testDome {
    public static int binarySearch(int aimValue,int left,int right,int[] arr ) {
        if(left<=right) {
            int mid = (left + right) / 2;
            if (aimValue > arr[mid]) {
                return binarySearch(aimValue,mid+1,right,arr);
            } else if(aimValue < arr[mid]){
                return binarySearch(aimValue,left,mid-1,arr);
            }else{
                return mid;
            }
        } return -1;
    }
    public static void main(String[] args){
        int[] arr ={1,2,13,24,35,36,48,49,56};
        int index = binarySearch(36,0,arr.length-1, arr);
        if(index >=0) {
            System.out.println("存在,下标是"+index);
        }else{
            System.out.println("该数不存在");
        }
    }

 代码已经运行,正确。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值