JAVA RECURSION An array is sorted in ascending order if each
JAVA RECURSION: 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 RECURSIVE 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
// Sorted.java
public class Sorted
{
// recursive function to check if array is sorted
public static boolean isSorted(int[] a, int size)
{
// less than 2 elements or no elements in array is sorted
if (a == null || size < 2)
{
return true;
}
else if (a[size - 2] > a[size - 1])
{
// if one unordered element is found
return false;
}
// else recursively call the function
return isSorted(a, size - 1);
}
public static void main(String[] args)
{
int arr[] = {1,3,9,0};
int n = arr.length;
if (isSorted(arr,n) ==true)
{
System.out.println(\"Array is sorted\ \");
}
else
System.out.println(\"Array is not sorted\ \");
}
}
