In: Computer Science
Problem 3: The IsSorted class [30’]
Description:
This Java program will create an integer array object with arbitrary elements, and judge whether this array is sorted (non-decreasing). For example, array1 {2,3,1,0} is not sorted, while array2 {5, 8,10,12,15} is sorted.
You may assume the array is non-empty.
Specifications:
In addition to the main method, you need to create another method
main Method
isSorted Method
The isSorted() method takes in an array of integers as a parameter. It checks whether all elements in this array are sorted (arranged in non- decreasing order) or not, and return true or false.
Output
Your output should look something like follows:
//Suppose the array is [5, 0, 2, 3, 8]
$java IsSorted
The array is not sorted.
//Suppose the array is [1, 1]
$java IsSorted
The array is sorted.
//Suppose the array is [2, 6, 10, 15, 20]
$java IsSorted
The array is sorted.
//Suppose the array is [7, 4, 3, 0]
$java IsSorted
The array is not sorted.
thanks for the question, here is the fully implemented class in Java
=====================================================================================
import java.util.Arrays;
import java.util.Random;
public class IsSorted {
private static final int
SIZE = 4;
public static void
main(String[] args) {
int
numbers[] = new
int[SIZE];
Random random =
new Random();
for
(int index = 0; index <
SIZE; index++) {
numbers[index] = random.nextInt(10);
}
System.out.println(Arrays.toString(numbers));
boolean
isSorted = isSorted(numbers);
if(isSorted){
System.out.println("The array is
sorted");
}else
{
System.out.println("The array is
not sorted");
}
}
public static boolean
isSorted(int[] numbers) {
for
(int index = 0; index <
numbers.length - 1; index++) {
if (numbers[index] > numbers[index + 1])
{
return false;
}
}
return
true;
}
}
