java递归的思想_Java - 递归思想

/*** 简单实现阶乘

*@paramn

*@return

*/

public static double getFactorial(doublen) {for(double i = n - 1;i > 0;i--){

n*=i;

}returnn;

}/*** 求阶乘

* n!=n*(n-1)*(n-2)*...*1

*@paramn

*@return

*/

public static int getFactorialValue(intn){if(n == 1){return 1;

}else{return getFactorialValue(n -1)*n;

}

}/*** 用递归实现斐波那契数列,适用于求解比较小的位置数值

* 0 1 1 2 3 5 8 13 21...

*@paramn

*@return

*/

public static int getFibonacciValue(intn){if(n<=0) return 0;if(n<=2){return 1;

}else{return getFibonacciValue(n-1) + getFibonacciValue(n-2);

}

}/*** 列出某个目录下所有子目录和文件

*@parampath

*@return

*/

public static void getDir(String path) throwsException{

File file= newFile(path);if(file.isDirectory()){

System.out.println("Dir" +file.getPath());

File[] fileArr=file.listFiles();for(File f : fileArr) {

getDir(f.getPath());

}

}else if(file.isFile()){

System.out.println("File" +file.getPath());

}else{throw new Exception(file.getPath() + "非Dir非File?!");

}

}/*** 汉诺塔

* func:

* if n!=0 then ;预定值

* func(n-1, a, c, b) ;将n-1个盘子由a移动到b,以c为辅助柱子(注意参数顺序)

* move a[n] to c ;将a上的最后一个盘子移动到c

* func(n-1, b, a, c) ;将n-1个盘子由b移动到c,以a为辅助柱子

* endif ;完成

*@paramn

*@parama

*@paramb

*@paramc*/

public static void getHanoi(intn, String a, String b, String c){if(n == 1){

System.out.println("移动盘子 " + n + " 从 " + a + " 到 " +c);

}else{

getHanoi(n-1, a, c, b);

System.out.println("移动盘子 " + n + " 从 " + a + " 到 " +c);

getHanoi(n-1, b, a, c);

}

}/*** 二分法查找值 : 原理就是找中间值

* 一定是有序表,升序降序都可以

*

*@paramarray 有序数组,但不限于数组

*@paramstart 开始查找的数组下标

*@paramend 结束查找的数组下标

*@paramsearchValue 要搜索的值

*@return

*/

public static int search(int[] array, int start, int end, intsearchValue){if (array != null && array.length > 0){int middle = (start + end) / 2;int middleValue =array[middle];if (searchValue ==middleValue){returnmiddle;

}else if (searchValue

return search(array, start, middle-1, searchValue);

}else{//查询值大于中值,在中值后面再次搜索,缩小范围

return search(array, middle+1, end, searchValue);

}

}else{return -1;

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值