write the definition of a static method named isSorted that receives a fully pop
ID: 3660393 • Letter: W
Question
write the definition of a static method named isSorted that receives a fully populated array of references to object 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 otherExplanation / Answer
import java.util.Arrays;
public class dummy
{
public static void main(String[] args)
{
int a[] = {0,1,2};
int n=isSorted(a);
System.out.println("Value returned = "+ n);
}
private static int isSorted(int[] a)
{
int []temp = new int[a.length];
int k=-1;
if (a.length==0 || a.length==1) return 1;
for (int i=0;i<a.length;i++)
if (a[i]==a[0]) k=1;
else { k=0;break; }
if (k==1) return 1;
for (int i=0;i<a.length;i++) temp[i]=a[i];
Arrays.sort(temp);
for (int i=0;i<a.length;i++)
if (a[i]==temp[i]) k=1;
else { k=0;break; }
if (k==1) return 1;
for (int i=0;i<a.length;i++)
if (a[i]==temp[a.length-i-1]) k=1;
else { k=0;break; }
if (k==1) return 2;
return 0;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.