遞歸打印數字:java
package test; public class Recursion1 { public static void main(String[] args) { // TODO Auto-generated method stub printOut(345423456); } /** * * @param n */ public static void printOut(int n){ if(n > 10){ printOut(n/10); // 遞歸體,總能想一個基準狀況靠攏 } System.out.print(n%10);// 基準狀況 } }
遞歸求解最大子序列:code
public static int maxSubSum4(int[] a,int left, int right){ int leftMaxSum=0,rightMaxSum=0,leftTempSum=0,rightTempSum=0; int center = (left+right)/2; //基本狀況 if(left == right){ return a[left]>0?a[left]:0; } //左邊包括最後一個元素的最大和 for(int i=center; i>=left; i--){ leftTempSum += a[i]; if(leftTempSum>leftMaxSum){ leftMaxSum = leftTempSum; } } //右邊包括第一個元素的最大和 for(int i=center+1; i<=right; i++){ rightTempSum += a[i]; if(rightTempSum>rightMaxSum){ rightMaxSum = rightTempSum; } } //左邊最大和(遞歸) int leftMax = maxSubSum4(a, left, center); //右邊最大和(遞歸) int rightMax = maxSubSum4(a, center+1, right); return max3( leftMax, rightMax, leftMaxSum + rightMaxSum ); } private static int max3( int a, int b, int c ) { return a > b ? a > c ? a : c : b > c ? b : c; }
遞歸折半查找:blog
public class Dgzbcz { public static void main(String[] args) { // TODO Auto-generated method stub Integer[] arr = {-3,-2,-2,-1,2,4,5,6}; int index = bannarySearch(arr,-2,0,arr.length-1); System.out.println(index); } public static <AnyType extends Comparable<? super AnyType>> int bannarySearch(AnyType[] a,AnyType x,int low,int hight){ // 不斷推動 int mid = (low+hight)/2; // 基本狀況1 if(a[mid].compareTo(x)==0){ return mid; } // 基本狀況2 if(low == hight){ return -1; } // 不斷推動 return a[mid].compareTo(x)>0?bannarySearch(a,x,low,mid):bannarySearch(a,x,mid+1,hight); } }