Java:使用递归检查数组是否已订购

时间:2016-10-08 21:00:45

标签: java recursion

我正在尝试了解递归。我想检查一个数组是否使用递归进行排序,但是我的代码存在一些问题,因为当index达到值2时,下一步应该是达到基本情况,但事实并非如此。这是我的代码,我做错了什么?

public class ArrayOrdered {

    public static boolean isArrayInSortedOrder(int[] array, int index)
    {
        boolean b;
        int a1;
        int a2;

        if(array.length == 1 || index == 1){//base case
            b=true;
        }else{
            b=false;
            a1 = array[index - 1];
            a2 = array[index - 2];
            if((a1 > a2)){//ordered
                isArrayInSortedOrder(array, index - 1);
            }   
        }

        return b; 
    }

    public static void main(String[] args) {
        int index=20;
        int[] array={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
        boolean bool = isArrayInSortedOrder(array, index);
        if(bool)
            System.out.println("Array ordered");
        if(!bool)
            System.out.println("Array NO ordered");
    }

}

2 个答案:

答案 0 :(得分:1)

您正在调用isArrayInSortedOrder(array, index - 1),但忽略它的返回值。请考虑以下事项:

public static boolean isArrayInSortedOrder (int[] array, int index) {
    if (array.length == 1 || index == 1) { //base case
        return true;
    }

    int a1 = array[index - 1];
    int a2 = array[index - 2];
    if (a1 > a2) {
        return isArrayInSortedOrder(array, index - 1);
    }   

    return false;
}

答案 1 :(得分:1)

如果他们使代码更难阅读,我会尝试避免临时值。您还需要返回 recurse 的值(或者无法按照您想要的方式工作)。像

这样的东西
public static boolean isArrayInSortedOrder(int[] array, int index) {
    if (array == null || array.length < 2 || index < 2) {
        return true;
    }
    if (array[index - 1] > array[index - 2]) {
        return isArrayInSortedOrder(array, index - 1);
    }
    return false;
}

当您致电时,我更愿意使用array.length(而不是使用index对其进行硬编码)。

boolean bool = isArrayInSortedOrder(array, array.length);
相关问题