JAVA help me. write the definition of a static method named isSorted that receiv
ID: 3581409 • Letter: J
Question
JAVA help me.
write the definition of a static method named isSorted that receives a fully populated array of references to objects that implement the Comparable interface. It returns an int. The returned value will be = 0 if the object referenced in the array are not sorted. The value will be 1 if the object referenced in the array are in ascending order. On the other hand, the returned value will be 2 if the objects are in descending order. The method also returns 1 for the arrays length 0 or 1, and when all elements equal each other.
Algorithm use a for loop and two flags, ascending and descending While in the loop, set the appropriate flag if adjacent elements are ascending or descending After the loop finishes test the flags to see which one (s) is/are true and return the required value.) public static int is Sorted (Comparable list boolean ascending false: boolean descending false; if (list return 1 for (int i 1 i list lenght i++ if (list 1. list 1) 0) true; if return 0; if return 1 if return 2 return.Explanation / Answer
Hi, Please find my implementation.
It is working in all cases.
Please let me know in case of any issue.
public class Test {
public static int isSorted(Comparable[] list){
boolean ascending = true;
boolean descending = true;
if(list.length <=1 )
return 1;
for(int i=1; i<list.length; i++){
if(list[i-1].compareTo(list[i]) <= 0)
ascending = ascending && true;
else
ascending = false;
if(list[i-1].compareTo(list[i]) >= 0)
descending = descending && true;
else
descending = false;
}
if(!ascending && !descending)
return 0;
if(ascending)
return 1;
if(descending)
return 2;
return 1;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.