資料結構與演算法-->遞迴
阿新 • • 發佈:2018-12-05

遞迴列印數字:
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);
}
}
