Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write the following method that returns true if the list is already sorted in no

ID: 3885771 • Letter: W

Question

Write the following method that returns true if the list is already sorted in nondecreasing order: 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 program first prompts the user to enter the size of the list. Enter the size of the list: 8 Enter the contents of the list: 10 1 5 16 61 9 11 1 The list has 8 integers 10 1 5 16 61 9 11 1 The list is not sorted Enter the size of the list: 10 Enter the contents of the list: 1 1 3 4 4 5 7 9 11 21 The 1ist has 10 integers 1 1 3 4 4 5 7 9 11 21 The list is already sorted

Explanation / Answer

Sample Output

import java.util.Scanner;
class Main{
public static boolean isSorted(int[] list)
{
int x = list[0];
boolean result = true;
  
System.out.printf("The list has %d integers ",list.length);
for(int num: list)
{
// checking if previous number is bigger
if(x>num)
{
result = false;
}
System.out.printf("%d ",num);
}
  
// printint output
if(result == true)
{
System.out.println(" The list is already sorted");
}
else
{
System.out.println(" The list is not sorted");
}
return result;
}
public static void main(String[] args)
{
int n;
Scanner sc = new Scanner(System.in);
  
// taking user input
System.out.print("Enter the size of the list: ");
n=sc.nextInt();
int [] a = new int[n];
System.out.print("Enter the contents of the list: ");
for (int i = 0; i < n; i++) {
   if (sc.hasNextInt()) {
       a[i] = sc.nextInt();
   }
}
isSorted(a);
}
}

Sample Output

  Enter the size of the list:  8  Enter the contents of the list:  10 1 5 16 61 9 11 1  The list has 8 integers 10 1 5 16 61 9 11 1   The list is not sorted  
  Enter the size of the list:  10  Enter the contents of the list:  1 1 3 4 4 5 7 9 11 21  The list has 10 integers 1 1 3 4 4 5 7 9 11 21   The list is already sorted