-2

I am creating code to check if an array is in ascending order. I have created code that seems logical to me; however, when I input an array that is in ascending order, I receive an error message (but when I input an array that is not in ascending order, the code outputs "false, as it should). Here is my code:

public class Ordered {
  public static boolean isSorted(int[] numbers) {
    int length = numbers.length;  
    for (int i=0; i <= length-1; i++) {
      if (numbers[i] > numbers[i+1]) { //here is where I think the error message is showing the issue is
        return false;
      }  
    }
    return true;     
  }
} 
SneSar
  • 3
  • 2
  • 1
    What is the error message? – xTwisteDx Apr 15 '21 at 18:42
  • Please see the [How to Ask](https://stackoverflow.com/help/how-to-ask) page. It's a good idea to post the errors when you get the errors. Also: consider what happens when you're at `length - 1`, recalling that Java arrays are 0-indexed. – Dave Newton Apr 15 '21 at 18:42
  • 3
    When you get to the last index of the array, you're checking i+1 which is probably giving you an ArrayIndexOutOfBounds exception. – cwittah Apr 15 '21 at 18:43

3 Answers3

0

Try this, so you don't go beyond the last index of the array:

public static boolean isSorted(int[] numbers) {
    int length = numbers.length;  
    for (int i=0; i < length-1; i++) {
        if (numbers[i] > numbers[i+1]) { 
            return false;
        }  
    }
    return true;     
}
cwittah
  • 349
  • 1
  • 3
  • 17
0

You must be getting an ArrayIndexOutOfBoundsException at the if (numbers[i] > numbers[i + 1]) condition.

Loop until, i < length - 1 and not until i <= length - 1

public static boolean isSorted(int[] numbers) {
    int length = numbers.length;
    for (int i = 0; i < length - 1; i++) {
        if (numbers[i] > numbers[i + 1]) {
            return false;
        }
    }
    return true;
}
  • Thank you! That seemed to solve my issue. However, I am confused as to why it should not be i<= length -1. – SneSar Apr 15 '21 at 20:39
  • Let's say if the length is 6. When i is 5, i<= length -1 evaluates to true. In the next, if statement when you access numbers[i + 1], Java throws ArrayIndexOutOfBoundsException because you are accessing index 6, but for an array of length indexes are allowed from 0 to 5. – Vikrant Wagh Apr 16 '21 at 05:10
0

THis will work because numbers[i + 1] should always be last element of the array if all prev are in ascending orders.

public static boolean isSorted(int[] numbers) {

for (int i = 0; i < numbers.length - 2; i++) {
    if (numbers[i] > numbers[i + 1]) {
        return false;
    }
}
return true;

}