An array is sorted (in ascending order) if each element of the array is less than or equal to the next element.
Write a boolean-valued method named isSorted that accepts an integer array, and the number of elements in the array and returns whether the array is sorted.
Need this to be in Java programming language.
Answer:
I have written the Java Function and it is working perfectly!!!
Code:
import java.io.*;
import java.util.*;
class Test
{
public static boolean isSorted(int[] arr,int
size)
{
if(size==0 || size==1)
{
return
true;
}
for(int i=0;i<size-1;i++)
{
if(arr[i]>arr[i+1])
{
return false;
}
}
return true;
}
public static void main(String[] args)
{
int[] arr={1,2,3,4,5};
if(isSorted(arr,5))
{
System.out.println("Sorted !!!");
}
else
{
System.out.println("Not Sorted !!!");
}
}
}
Get Answers For Free
Most questions answered within 1 hours.