Answer:
The program is as follows:
import java.util.Scanner;
public class MyClass {
public static Boolean isSorted(int [] arr){
Boolean sorted = true;
for(int i = 0;i<arr.length;i++){
for(int j = i;j<arr.length;j++){
if(arr[i]>arr[j]){
sorted = false;
break;
}
}
}
return sorted;
}
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
int n;
System.out.print("Length of array: ");
n = input.nextInt();
int[] arr = new int[n];
System.out.println("Enter array elements:");
for(int i = 0; i<n;i++){
arr[i] = input.nextInt();
}
Boolean chk = isSorted(arr);
System.out.print(chk);
}
}
Step-by-step explanation:
The method begins here
This line defines a method named isSorted
public static Boolean isSorted(int [] arr){
This line declares a boolean variable and initializes it to true
Boolean sorted = true;
The next two iterations iterate through elements of the array
for(int i = 0;i<arr.length;i++){
for(int j = i;j<arr.length;j++){
This compares an array element with next elements (to the right)
if(arr[i]>arr[j]){
If the next element is smaller than the previous array element, then the array is not sorted
sorted = false; The boolean variable is updated to false
break; This breaks the loop
}
}
}
This returns true or false, depending on the order of the array
return sorted;
}
The main method begins here
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
int n;
This prompts user for length of array
System.out.print("Length of array: ");
This gets length of array from user
n = input.nextInt();
This declares an array
int[] arr = new int[n];
This prompts user for array elements
System.out.println("Enter array elements:");
The following iteration gets the array elements
for(int i = 0; i<n;i++){
arr[i] = input.nextInt();
}
This calls the isSorted array
Boolean chk = isSorted(arr);
This prints true or false, depending if the array is sorted or not
System.out.print(chk);
}