1

I am recently finished creating a program that checks if a user-inputted int array is arranged in ascending order. I have my function isAsc here:

public static boolean isAsc(int[] arr, int index){
    if (index==1 || arr.length==1){
        return true; //Base case
    }
    else if (arr[index-2] >= arr[index-1]){
        return false; 
    }
    else
        return isAsc(arr, index-1); //recursive step
}

And the logic seems to be correct. However, what I don't get is when I call the function: System.out.print(isAsc(arr, arrayLength-1));

the output is wrong. This System.out.print(isAsc(arr, arrayLength)); yields the correct answer. Why? Thanks!

5
  • 2
    What is the output you see? What is the array you used? Commented Jan 29, 2017 at 10:00
  • Your logic returns false when there are duplicate numbers, even though they are sorted correctly (adjacent). Change >= to >. Commented Jan 29, 2017 at 10:05
  • @Malvolio 1 2 4 3 and it returns true. anyways, i got it figured out now thanks Commented Jan 29, 2017 at 10:10
  • @Bohemian, yes I made it like that. Commented Jan 29, 2017 at 10:10
  • @PaulStevenFantonalgoNadera -- your error is so common, it has its own Wikipedia page. Commented Jan 29, 2017 at 18:32

1 Answer 1

3

If you are calling the method with

isAsc(arr, arr.length-1)

your method never checks the last element of the array in the if (arr[index-2] >= arr[index-1]) check, so the output may be incorrect.

On the other hand, when you call it with

isAsc(arr, arr.length)

the first execution of your method checks if (arr[index-2] >= arr[index-1]), or in other words if (arr[arr.length-2] >= arr[arr.length-1]) (assuming your array has multiple elements), so arr[arr.length-1] is not skipped.

Sign up to request clarification or add additional context in comments.

2 Comments

Ohhhh, I got it now. I had to write everything with pen and paper to understand, lol. Thank you very much!
I should've used index-1 >= index instead lol I'm used to declaring arr.length-1. thanks again

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.