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.length; i++) { if(data[i-1] > 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.length; i++) { if(previous > 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.