Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

(Intro to Java help?) Write a static method named isSorted that takes an array o

ID: 3699323 • Letter: #

Question

(Intro to Java help?)

Write a static method named isSorted that takes an array of real numbers as a parameter and that returns true if the list is in sorted (nondecreasing) order and false otherwise. For example, if variables named list1 and list2 refer to arrays containing {16.1, 12.3, 22.2, 14.4} and {1.5, 4.3, 7.0, 19.5, 25.1, 46.2} respectively, the calls of isSorted(list1) and isSorted(list2) should return false and true respectively. Assume the array has at least one element. A one-element array is considered to be sorted.

Test your code with the following class:

public class TestIsSorted {

    public static void main(String[] args) {

        double[] a1 = {16.1, 25.3, 12.2, 44.4};

        double[] a2 = {1.5, 4.3, 7.0, 19.5, 25.1, 46.2};

        double[] a3 = {42.0};

        System.out.println(isSorted(a1)); // false

        System.out.println(isSorted(a2)); // true

        System.out.println(isSorted(a3)); // true

    }

    // your code goes here

}

Explanation / Answer

public class TestIsSorted {
    public static void main(String[] args) {
        double[] a1 = {16.1, 25.3, 12.2, 44.4};
        double[] a2 = {1.5, 4.3, 7.0, 19.5, 25.1, 46.2};
        double[] a3 = {42.0};
        System.out.println(isSorted(a1)); // false
        System.out.println(isSorted(a2)); // true
        System.out.println(isSorted(a3)); // true
    }
   
    public static boolean isSorted(double a[])
{
int flag = 0; // flag value 0 denotes array is sorted
for(int i=0;i<a.length-1;i++)
{
  for(int j=i+1;j<a.length;j++)
  {
  if(a[i] > a[j]) // if any element is array is greater than its successor
  flag = 1; // set flag =1
  }
}
if(flag == 0)
return true;
else
return false;
}

   
}

Output:

false
true
true

Do ask if any doubt. Please upvote.