Is the pair 23 23 out of order?
No.
You will need to be careful with comparison operators like <
and <=
because of this.
public class IsSorted { // Determine if an array is sorted in ascending order // public static boolean isSorted( int[] array ) { boolean inOrder = true; // scan the list starting at index 0 for ( int j=0; j<array.length-1 && inOrder; j++ ) { // check the pair starting at j inOrder = array[j] <= array[j+1]; } return inOrder; } public static void main ( String[] args ) { int[] values = {12, 23, -5, 56, 32, 17, -4, -49, -1, -23, 45 }; // print out the array System.out.println("values: "); for ( int val : values ) System.out.print( val + ", " ); System.out.println( ); // determine if it is in order if ( isSorted(values) ) System.out.println( "Is in order" ); else System.out.println( "Is NOT in order" ); } }
This program that determines if an array of int
is in ascending order.
This is a little silly because the array is hard-coded into the program.
But pretend that the array came from some external data source,
perhaps from a file,
and that the program needed to check that it was in order before proceeding.
The method isSorted()
implements the algorithm.
For each pair of integers starting at the left: if any pair is out of order, the list is not in order
Each pair of integers is tested, starting with the pair at index 0 and index 1, then testing the pair at index 1 and index 2, and so on.
BUG ALERT: The last pair consists of the integers at
array.length-2
and array.length-1
,
so the loop ending condition must test
j<array.length-1
It is easy to forget the -1
Does the following statement correctly check that the pair beginning at j
is in order?
inOrder = array[j] <= array[j+1];