jose jose - 1 month ago 14
Java Question

Java: Use recursion to check if an array is ordered

I am trying to learn about recursion. I want to check if an array is ordered using recursion, but there is something that is wrong with my code because when index reaches the value 2, the next step should be to reach the base case but it doesn't. Here is my code, what am I doing wrong?

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");
}

}

Answer

You are calling isArrayInSortedOrder(array, index - 1), but ignoring it's return value. Consider the following:

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;
}
Comments