HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaModerate

Checking if an array is sorted

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
arraycheckingsorted

Problem

I've come up with two ways to check to see if array is sorted and return true if it is.

public static boolean checkSortedness(int[] data)
{
    for(int i = 1; i  data[i])
        {
            return false;
        }
    }
    return true;
}


I've also seen the i start at 0 and compare the next element instead of the previous. The other way which involves another variable is

public static boolean isSorted(int[] data)
{
     int previous = data[0];
     for(int i = 1; i  data[i])
             return false;
         previous = data[i];
     }
     return true;
}


Which way is better and are there any alternatives?

What should the array parameter be named? I call it data but I've considered arr. This class is meant to be fairly generic.

Solution

Three other answers, and none have picked up on the bug yet, so, here's the bug, in the second version:

The input array new int[]{4} is sorted, right? The first method will return true. The second method will return true, fine... but, what about the array new int[]{} (the empty array)? The first method will return true. The second method will throw ArrayIndexOutOfBoundsException

The two methods are not the same. The second is buggy.

To me, this makes the first method the clear winner.

Now, while you are reading this, also note that in Java, the { brace should, by convention, be at the end of a line, not on a new line. What you have in your code is C* style coding (C, C++, C#, etc.).

Also, use final when appropriate....

Your code should look like:

public static final boolean checkSortedness(final int[] data) {
    for(int i = 1; i  data[i]) {
            return false;
        }
    }
    return true;
}

Code Snippets

public static final boolean checkSortedness(final int[] data) {
    for(int i = 1; i < data.length; i++) {
        if(data[i-1] > data[i]) {
            return false;
        }
    }
    return true;
}

Context

StackExchange Code Review Q#58533, answer score: 14

Revisions (0)

No revisions yet.