JAVA An array is sorted in ascending order if each element o

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

Hi, Please find my program.

Please let me know in case of any issue.

public class Test {

  

// function to check whether array is sorted or not

public static boolean isSorted(int[] arr, int size){

      

       // base case

       if(arr==null || size <=1)

           return true;

      

       // iterate from 0 to size-2

       for(int i=0; i<size-1; i++){

          

           // if elements are out of order then return false

           if(arr[i] > arr[i+1])

               return false;

       }

      

       // reach here means all elements are in order

       return true;

   }

  

   public static void main(String[] args) {

      

       int[] arr1 = {1,2,3,4,4,6,5};

       int arr2[] = {4,5,6,7,8,9};

      

       System.out.println(isSorted(arr1, 7));

       System.out.println(isSorted(arr2, 6));

      

      

   }

}

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
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

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site