Programming Examples
Java program to check array is sorted or not if sorted then tell where in ascending order or descending
Write a java program to check whether an elements of an array are sorted or not if sorted then print the sorted order.
Solution:
import java.util.*;
class Sorted
{
public static void main(String arr[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the size of Array : min(2) ");
int size=sc.nextInt();
int num[]=new int[size];
System.out.println("Enter "+size+" Elements for Array :");
for(int i=0;i<size;i++)
{
num[i]=sc.nextInt();
}
boolean asc=true;
boolean desc=true;
if(size<2)
{
System.out.println("Invalid Size of Array minimum is 2 ");
System.exit(0);
}
if(num[0]>num[1]) // checking for ascending order if size of array is <3
{
asc=false;
}
if(num[0]<num[1]) // checking for descending order if size of array is <3
{
desc=false;
}
for(int i=0;i<size-1;i++)
{
if(num[i]>num[i+1]) // checking for ascending order
{
asc=false;
}
if(num[i]<num[i+1]) // checking for descending order
{
desc=false;
}
}
if(asc==true)
{
System.out.println("Sorted in Ascending Order");
}
else if(desc==true)
{
System.out.println("Sorted in Descending Order");
}
else
{
System.out.println("Array is not Sorted");
}
}
}
Output
Enter the size of Array :
5
Enter 5 Elements for Array :
1
2
3
4
5
Sorted in Ascending Order
Enter the size of Array :
5
Enter 5 Elements for Array :
7
6
5
4
3
Sorted in Descending Order
Enter the size of Array :
3
Enter 3 Elements for Array :
4
2
4
Array is not Sorted