蓝桥 第二周 递归

递归

        找重复->找重复中的变化量->参数变化趋势

数组求和

public static void main(String[] args) {
        int[] arr = {1,2,3,4,5,6,7,8,9,10};
        int n = arr.length;
        System.out.println(sum(arr,0,n));
    }
    public static int sum(int arr[],int start,int end){
        if(start == end-1)return arr[start];
        else return arr[start] + sum(arr,start+1, end);
    }

翻转字符串

public static void main(String[] args) {
        StringBuffer s = new StringBuffer("abcdef");
        System.out.println(reversestr(s,0,s.length()));
    }
    public static StringBuffer reversestr(StringBuffer str,int start,int end){
        if(start==end-1){
            StringBuffer res = new StringBuffer(String.valueOf(str.charAt(start)));
            return res;
        }else{
            return reversestr(str,start+1,end).append(str.charAt(start));
        }
    }

斐波那契数列

public static void main(String[] args) {
        for(int i=1;i<10;i++) System.out.println(fib(i));
    }
public static int fib(int n){
    if(n==1)return 1;
    else if(n==2)return 1;
    else return fib(n-1)+fib(n-2);
}

最大公约数

    public static void main(String[] args) {
        System.out.println(gcd(10,20));
    }
    public static int gcd(int m,int n){
        if(n==0)return m;
        else return gcd(n,m%n);
    }

递归形式进行插入排序

    public static void main(String[] args) {
        int[] arr = {1,5,2,6,3,9,11};
        sort1(arr,arr.length-1);
        for(int i=0;iarr[idx]){
                arr[i+1]=arr[i];
                i--;
            }
            arr[i+1]=temp;
        }
    }

汉诺塔

    public static void main(String[] args) {
        hanoi(3,'a','b','c');
    }
    public static void hanoi(int n,char c1, char c2, char c3){
        if(n==1)System.out.println(""+c1+"->"+c3);
        else{
            hanoi(n-1,c1,c3,c2);
            System.out.println(""+c1+"->"+c3);
            hanoi(n-1,c2,c1,c3);
        }
    }

递归二分查找

	public static int binarySearch(int[] arr,int target, int low,int high) {
		if(low>high)return -1;
		int mid = low + (high - low)/2;
		if(arr[mid]==target) return mid;
		else if(arr[mid]>target)return binarySearch(arr,target,low,mid-1);
		else return binarySearch(arr,target,mid+1,high);
	}

希尔排序

	public static void shellSort(int[] arr) {
		int n = arr.length;		
		for(int interval = arr.length/2;interval>0;interval/=2) {
			for(int i=interval;i=0&&arr[j]>target) {
					arr[j+interval] = arr[j];
					j-=interval;
				}
				arr[j+interval] = target;
			}
		}		
	}

算法复杂度

        线性、平方、对数

你可能感兴趣的:(java,算法,数据结构)