Answer:
The java program for the given scenario is given below.
This program can be saved as HW2.java.
import java.util.Scanner;
public class HW2 {
public static void main(String args[]) {
HW2 ob = new HW2();
Scanner sc = new Scanner(System.in);
int len;
System.out.println( "Enter the number of elements to be entered in the array");
len = sc.nextInt();
int[] arr = new int[len];
System.out.println( "Enter the elements in the array");
for( int k=0; k<len; k++ )
{
arr[k] = sc.nextInt();
}
boolean sort = ob.isSorted(arr, len);
System.out.println( "The elements of the array are sorted: " + sort );
}
public boolean isSorted( int a[], int l )
{
int sort = 0;
if( l==1 )
return true;
else
{
for( int k=1; k<l; k++ )
{
if(a[k-1] < a[k])
continue;
else
{
sort = sort + 1;
break;
}
}
if(sort == 0)
return true;
else
return false;
}
}
}
OUTPUT
Enter the number of elements to be entered in the array
3
Enter the elements in the array
1
2
1
The elements of the array are sorted: false
Step-by-step explanation:
1. First, integer variable, len, is declared for length of array. User input is taken for this variable.
2. Next, integer array is declared having the size, len. The user is prompted to enter the equivalent number of values for the array.
3. These values are directly stored in the array.
4. Next, the function isSorted() is called.
5. This method uses an integer variable sort which is declared and initialized to 0.
6. Inside for loop, all elements of the array are tested for ascending order. If the 1st and 2nd elements are sorted, the loop will continue else the variable sort is incremented by 1 and the loop is terminated.
7. Other values of the variable sort indicates array is not sorted.
8. A Boolean variable, sort, is declared to store the result returned by isSorted method.
9. Lastly, the message is displayed on the output whether the array is sorted in ascending order or not.