Use recursion to determine whether an array is ordered

package shujujiegou;
//判断数组是否有序;

public class digui1 {

    public static void main(String[] args) {
        int[] arr1 = {1, 2, 3, 4, 50};

        int[] arr2;
        arr2 = new int[]{12, 3, 5, 5};
        System.out.println(panduanyouxu(arr1, 5));
        System.out.println(panduanyouxu(arr2, 4));

    }

    public static boolean panduanyouxu ( int[] arr, int index){
        if (index == 1) {
            return true;
        }
        return (arr[index - 1] <= arr[index - 2]) ? false : panduanyouxu(arr, index - 1);
    }
}

Some blogs and books say something like this:


    public static boolean panduanyouxu ( int[] arr, int index){
        if (arr.length == 1) { //注意这一行
            return true;
        }
        return (arr[index - 1] <= arr[index - 2]) ? false : panduanyouxu(arr, index - 1);
    }

   The length of arr.length is always the same, and there will be an infinite loop.

 

Please correct me if I am wrong

Guess you like

Origin blog.csdn.net/GuiMa005/article/details/104612676