Please Write in Java An array is sorted in ascending order i

Please Write in Java

An array is sorted (in ascending order) if each element of the array is less than or equal to the next element .

An array of size 0 or 1 is sorted

Compare the first two elements of the array ; if they are out of order, the array is not sorted; otherwise, check the if the rest of the array is sorted.

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.

Solution

SortCheck.java


public class SortCheck {

  
   public static void main(String[] args) {
       System.out.println(isSorted(new int[]{1,2,3,4,5}, 5));
       System.out.println(isSorted(new int[]{1,2,4,3,5}, 5));
   }
   public static boolean isSorted(int a[], int size){
       if(size ==0 || size == 1){
           return true;
       }
       for(int i=0; i<size-1; i++){
           if(a[i] > a[i+1])
               return false;
       }
       return true;
   }

}

Output:

true
false

Please Write in Java An array is sorted (in ascending order) if each element of the array is less than or equal to the next element . An array of size 0 or 1 is

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site