Write a Java program 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, 41, 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.
I have this so far:
import java.util.Scanner;
public class Number2 {
public static void main(String[] args) {
int n;
int[] arr=null;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of elements in the array: ");
n = sc.nextInt();
System.out.println("Enter the elements in the array: ");
arr = new int[n];
for (int = 0; i < n; i++)
arr[i] = sc.nextInt();
if(isSorted(arr,n))
System.out.println("The elements in the array are sorted.");
else;
System.out.println("The elements in the array are not sorted");
}
}
import java.util.Scanner; public class Number2 { private static boolean isSorted(int[] arr, int n) { for(int i = 1;i<arr.length;i++){ if(arr[i-1] > arr[i]){ return false; } } return true; } public static void main(String[] args) { int n; int[] arr=null; Scanner sc = new Scanner(System.in); System.out.println("Enter the number of elements in the array: "); n = sc.nextInt(); System.out.println("Enter the elements in the array: "); arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = sc.nextInt(); if(isSorted(arr,n)) System.out.println("The elements in the array are sorted."); else System.out.println("The elements in the array are not sorted"); } }
Get Answers For Free
Most questions answered within 1 hours.