Check if an array is sorted, return true or false

user2101463 picture user2101463 · Oct 18, 2013 · Viewed 85.9k times · Source

I am writing an easy program the just returns true if an array is sorted else false and I keep getting an exception in eclipse and I just can't figure out why. I was wondering if someone could take a look at my code and kind of explain why I'm getting an array out of bounds exception.

public static boolean isSorted(int[] a) 
{
    int i;
    for(i = 0; i < a.length; i ++);{
        if (a[i] < a[i+1]) {
            return true;
        } else {
            return false;   
        }
    }
}
public static void main(String[] args)
{
    int ar[] = {3,5,6,7};
    System.out.println(isSorted(ar));   
}

Answer

Richard Tingle picture Richard Tingle · Oct 18, 2013

Let's look at a cleaner version of the loop you constructed:

for (i = 0; i < a.length; i++); { 
    if (a[i] < a[i + 1]) {
        return true;
    }
    else {
        return false;
    }
}

I should first point out the syntax error in the original loop. Namely, there is a semicolon (;) before the curly brace ({) that starts the body of the loop. That semicolon should be removed. Also note that I reformatted the white-space of the code to make it more readable.

Now let's discuss what happens inside your loop. The loop iterator i starts at 0 and ends at a.length - 1. Since i functions as an index of your array, it makes sense pointing out that a[0] is the first element and a[a.length - 1] the last element of your array. However, in the body of your loop you have written an index of i + 1 as well. This means that if i is equal to a.length - 1, your index is equal to a.length which is outside of the bounds of the array.

The function isSorted also has considerable problems as it returns true the first time a[i] < a[i+1] and false the first time it isn't; ergo it does not actually check if the array is sorted at all! Rather, it only checks if the first two entries are sorted.

A function with similar logic but which checks if the array really is sorted is

public static boolean isSorted(int[] a) {
// Our strategy will be to compare every element to its successor.
// The array is considered unsorted
// if a successor has a greater value than its predecessor.
// If we reach the end of the loop without finding that the array is unsorted,
// then it must be sorted instead.

// Note that we are always comparing an element to its successor.
// Because of this, we can end the loop after comparing 
// the second-last element to the last one.
// This means the loop iterator will end as an index of the second-last
// element of the array instead of the last one.
    for (int i = 0; i < a.length - 1; i++) {
        if (a[i] > a[i + 1]) {
            return false; // It is proven that the array is not sorted.
        }
    }

    return true; // If this part has been reached, the array must be sorted.
}