19.1k views
2 votes
Write a Java program HW2.java that asks the user to enter an array of integers in the main method. The program should prompt the user for the number of elements in the array and then the elements of the array. The program should then call a method named isSorted that accepts an array of and returns true if the list is in sorted (increasing) order and false otherwise. For example, if arrays named arr1 and arr2 store [10, 20, 30, 30, 56] and [2, 5, 3, 12, 10] respectively, the calls isSorted(arr1) and isSorted(arr2) should return true and false respectively. Assume the array has at least one element. A one-element array is considered to be sorted.

User Gliemezis
by
6.5k points

1 Answer

3 votes

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.

User Lutando
by
5.2k points