Java递归思想倒置数组

public class ReverseArry {
    public static void main(String[] args){
        int[] arr = {1,2,3,4,5,6,7,8,9};
        //System.out.println(arr.length);
        reverseArry(arr,0,arr.length-1);
        show(arr);
    }

    /*将n个问题的规模分解,第一次先将头尾两个交换即swap(lo,hi)
      剩下n-2的规模,面临的问题还是一样,采用递归的思想不断地减小
      问题的规模(减而治之)
    * */

    public static void reverseArry(int[] A, int lo, int hi){
        if (lo > hi || lo == hi){//问题规模的奇偶性不变,因为每次减少两个大小
            return;
        }
        if(lo < hi){
            swap(A, lo, hi);
        }
        reverseArry(A, ++lo, --hi);//递归一次,规模就缩小两个
    }

    public static void swap(int[] a, int i, int j){
        int temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }

    public static void show(int[] A){
        for(int i = 0; i < A.length; i++){
            System.out.print(A[i]+" ");
        }
    }
}

猜你喜欢

转载自blog.csdn.net/m0_37889791/article/details/85711776