1. 程式人生 > >將一個數組逆序-遞迴實現

將一個數組逆序-遞迴實現

題目:給定一個數組,逆序輸出。要求遞迴實現。

public class Main {
    public static void main(String[] args) {
        int[] arr = {1,2,6,5,4,4};
        getRes(arr);
    }

    public static void getRes(int[] arr) {
        getHelper(arr,0,arr.length-1);
    }

    public static void getHelper(int[] arr, int low, int high) {
        if(low >= high) {
            for (int i = 0; i < arr.length ; i++) {
                System.out.print(arr[i] + " ");
            }
            return;
        }
        else {
            int temp = arr[high];
            arr[high] = arr[low];
            arr[low] = temp;

            getHelper(arr,low+1,high-1);
        }
    }
}

說明:是不是覺得沒事撐著,陣列遍歷用得著這樣嗎,其實這是遞迴的思路,假如換做是連結串列呢,所以掌握思想永遠不會錯的。 注意事項:注意判斷條件是low >= high;而不是low = high。