2

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

}
1
  • 2
    change recursive , add return return isArrayInSortedOrder(array, index - 1); Commented Oct 8, 2016 at 21:03

2 Answers 2

1

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

This only verifies if the array is in Ascending order.
1

I would try and avoid temporary values if they make the code harder to read. You also need to return the value you recurse (or that won't work the way you want). Something like

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

And when you call it, I would prefer to use array.length (instead of hard coding it with index).

boolean bool = isArrayInSortedOrder(array, array.length);

1 Comment

Yes I was using temporary values just to debug the code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.