ObjecÂtive: Given an array of integer write a recursive solution to check if array is sorted.
Example:
int [] a = {1,2,3,4}; Output: true int [] a = {1,2,3,4,2}; Output: false
Approach: This problem can easily be solved in single iteration by just comparing adjacent elements. Fun part is to write the recursive solution. Code is self explanatory.
Code:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class IsSortedUsingRecursion { | |
public static boolean isSorted(int [] a, int start){ | |
if(start==a.length–1) | |
return true; | |
if(a[start]<=a[start+1]) | |
return isSorted(a, start+1); | |
else | |
return false; | |
} | |
public static void main(String[] args) { | |
int [] a = { 1,2,3,4,8,8,22,50}; | |
System.out.println(isSorted(a,0)); | |
} | |
} |
Output:
true