递归打印数字: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); } }