检查数组是否使用递归排序

Check if array is sorted using recursion

即使对于未排序的 (isNonDescending) 数组,我的答案也是正确的。错误在哪里? 我只想从数组的开头将数组分解成更小的问题。

//检查 isNonDescending。

public class AlgoAndDsClass {

    public static void main(String args[]) {

        int[] unsortedArry = { 1, 2, 3, 4 };
        int[] unsortedArry2 = { 1, 2, 4, 3 };
        System.out.println(isSorted(unsortedArry, unsortedArry.length));
       System.out.println(isSorted(unsortedArry2, unsortedArry2.length));


    }

    private static boolean isSorted(int[] arr, int size) {
        if (size == 0 || size == 1)
            return true;

        if (arr[0] > arr[1]) {
            return false;
        }
        System.out.println(arr.length);
        boolean smallwork = isSorted(arr, size - 1);

        return smallwork;

    }

您继续检查相同的 2 个元素,请尝试使用 size 变量代替数组索引。 例如,如果前 2 个元素被排序,你会得到 true,那是因为你只检查 arrray 中的前两个元素。

如果从开始到最后一个元素的 sub-array 已排序并且最后一个元素大于或等于最后一个元素之前的元素,则数组已排序。

与其将数组的大小作为参数传递,这无论如何都没有意义,因为您可以简单地调用 arr.length,您应该传递一个起始索引并在每次递归调用时增加它,直到您有达到了数组的长度。

private static boolean isSorted(int[] arr, int index) {
    if(arr.length == 0 || arr.length == 1 || index == arr.length - 1){
        return true;
    }
    if (arr[index] > arr[index + 1]) {
        return false;
    }
    return isSorted(arr, index + 1);
}

并以 0 作为起始索引从 main 调用

System.out.println(isSorted(unsortedArry,0));
System.out.println(isSorted(unsortedArry2,0));