递归打印数字:
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);// 基准情况
}
}
递归求解最大子序列:
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;
}
递归折半查找:
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);
}
}