Home / Data structures and Algorithms by Java Examples / Recursion / Is ArrayList Ordered using Recursion in JAVA Example
Is ArrayList Ordered using Recursion in JAVA Example
2134 views.
IsOrderedArrayList.java
import java.util.ArrayList;

class IsOrderedArrayList {
    /*
     * n == 1 return true;
     * (n-1 > n-2) ? T(n-1) : false;
     */
    static boolean isOrdered(ArrayList<Integer> arrayList,int index) {
        /* base case and initial case */
        if (arrayList.size() == 1 || index == 1) return true;
        
        /* recursive case */
        return (arrayList.get(index-1) > arrayList.get(index-2) ? isOrdered(arrayList,index-1) : false);
    }
    
    public static void main(String[] args) {
        //List of numbers
        ArrayList<Integer> arrayList = new ArrayList<Integer>();
        
        //Adding numbers to the arrayList.
        arrayList.add(4);
        arrayList.add(5);
        arrayList.add(6);
        arrayList.add(7);
        arrayList.add(8);
        
        //Calling isOrdered method
        boolean result = isOrdered(arrayList,arrayList.size());
        System.out.println(result);
    }
}
Output
true
Related Examples
   Simple Recursion Example in JAVA
   Print array using recursion JAVA Example
   Recursion on ArrayList Strings in JAVA Example
   Factorial Program using Recursion in JAVA Example
   Fibonacci Series using Recursion in JAVA Example
   Tree Traversal with Recursion in JAVA Example
   Tree Traversal without Recursion Using Stack Class in JAVA Example
   Is ArrayList Ordered using Recursion in JAVA Example
   Tower of Hanoi using Recursion in Java Example
Copyright © 2016 Learn by Examples, All rights reserved