1.用递归求最大值:
package Recursion; public class Demo1 { //用分治法找到最大值 public static void main(String[] args) { double[] a = new double[]{1,2,3,6,4,9,23,1,234}; double value = max(a,0,a.length-1); System.out.println(value); } static double max(double a[],int l,int r){ if(l==r)return a[l]; int m = (l+r)/2; double u = max(a,l,m); double v = max(a,m+1,r); if(u>v)return u; else return v; } }
package Recursion; import java.io.BufferedReader; import java.io.InputStreamReader; public class Demo2{ //汉诺塔,从A移到C public static void main(String[] args) throws Exception{ BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in)); System.out.println("请输入盘子的数目:"); int n = Integer.parseInt(buffer.readLine()); Demo2.move(n, 'A', 'B', 'C'); } public static void move(int n,char a,char b,char c){ if(n==1){ System.out.println("盘"+n+"由"+a+"移到"+c); }else { move(n-1,a,c,b); System.out.println("盘"+n+"由"+a+"移到"+c); move(n-1,b,a,c); } } }