算法笔记—04:递归算法的应用


递归:是指在定义自身的同时又出现了对自身的调用,典型的递归算法的应用有阶乘、斐波那契数列、汉诺塔、二分查找等等。下面给出各种函数的实现:


1.求阶乘

    /**
     * 求阶乘
     * n!=n*(n-1)*(n-2)*...*1
     */
	public static int fact(int n) {
		if(n == 1) {
			return 1;
		}else {
			return (n*fact(n-1));
		}
	}

2.斐波那契数列

    /**
	 * 斐波那契数列:0 1 1 2 3 5 8 13 21...
	 */
	public static int fibonacci(int n) {
		if(n == 0) return 0; 
		if(n == 1) return 1;
			
		return fibonacci(n-1) + fibonacci(n-2);
	}

3.汉诺塔

public class Main {
	public static void main(String[] args) {
		int i = 3;//盘子的数量
		char a = 'A', b = 'B', c = 'C';
		hanio(i,a,b,c);
	}
	public static void hanio(int n, char a, char b, char c) {
		if(n == 1) {
			System.out.println("移动"+n+"号盘子从"+a+"到"+c);
		}else {
			hanio(n-1, a, c, b);//把上面的n-1个盘子从a借助b搬到c
			System.out.println("移动"+n+"号盘子从"+a+"到"+c);//把n搬到c
			hanio(n-1, b, a, c);//再把b上的n-1个盘子借助a搬到c
		}
	}
}

4.二分查找(折半查找)

前提条件:待查找的表顺序存储而且表中的关键字大小有序排列

算法思路:

  1. 取待查范围中间位置的关键字与要查找的关键字进行比较,如果两者相等,则查找成功;
  2. 否则利用中间位置的关键字将表分成前、后两个子表;
  3. 如果中间位置的关键字大于查找关键字,则进一步查找前面子表;
  4. 否则(中间位置的关键字小于查找关键字),查找后面子表。
  5. 重复以上过程,直到找到或者不存在。

查找一个数在数组中的位置:

/*
 * 二分法查找值
 * 一定是有序表,升降序都可以
 * 原理就是找中间值
 */
public class Main {
	public static void main(String[] args) {
		//定义一个一维数组
		int[] array = {1,3,5,7,10,18,21,29,34,36,41,52};
		System.out.println(binarySearch(array, 0, array.length-1, 41));
	}
	/*
	 * array 有序数组;               start 开始查找的数组下标;
	 * end 结束查找的数组下标;  searchValue 要查找的值;
	 */
	private static int binarySearch(int[] array, int start, int end, int searchValue) {
		if(array != null && array.length > 0) {
			int middle = (start + end) / 2;
			int middleValue = array[middle];
			if(searchValue == middleValue) {
				return middle;
			}else if(searchValue < middleValue) {
				//如果查询值小于中间值,就在中间值的前半部分数搜索
				return binarySearch(array, start, middle-1, searchValue);
			}else {
				//如果查询值大于中间值,就在中间值的后半部分数搜索
				return binarySearch(array, middle+1, end, searchValue);
			}
		}else {
			return -1;
		}
	}
}

猜你喜欢

转载自blog.csdn.net/jingzhi111/article/details/88757113
今日推荐