The problem
Write the following method that returns true if the list is already sorted. public static boolean isSorted(int[] list)
Write a test program that prompts the user to enter a list and displays whether the list is sorted or not. Here is a sample run. Note that the first number in the input indicates the number of the elements in the list. This number is not part of the list.
Breaking it down
static int MAX_ARRAY_SIZE = 10;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("First number is size of list...");
System.out.print("Enter list: ");
MAX_ARRAY_SIZE = input.nextInt();
int[] numbers = new int[MAX_ARRAY_SIZE];
for (int i = 0; i < MAX_ARRAY_SIZE; i++) {
numbers[i] = input.nextInt();
}
input.close();
if (isSorted(numbers)) {
System.out.print("The list is sorted.");
} else {
System.out.print("The list is not sorted.");
}
}
public static boolean isSorted(int[] numbers) {
for (int i = 0; i < numbers.length - 1; i++) {
if (numbers[i] > numbers[i + 1])
return false;
}
return true;
}
Output
First number is size of list...
Enter list: 3
1
2
3
The list is sorted.