Friday 28 August 2015

Print the elements of the array in straight order and in reverse order using Recursion in Java

Hello friends,

I am here with another question in continuation to our simple recursive algorithm based questions.

If we have an array of numbers, we need to print the elements of the array in straight order and in reverse order. 

We can easily do this using iteration but for learning purpose lets try doing this using recursion.

Note that to print the elements in the reverse order I have used two methods, one uses simple index based manipulation but lets observe the other method : printReverseInterestingWay(). While other method prints the elements as it visits the element first time but this method prints the element during re-visit (following the recurrence method calls in stack)

Friends Please find the code below.

package com.recursion.printarray;

public class StraightReversePrintArray {
    public static void main(String[] args) {
        int[] input = { 1, 2, 3, 4, 6, 8 };
        int size = input.length;
        System.out.println("Straight printing of the Array: ");
        printStraight(input, size, 0);
        System.out.println("Reverse printing of the Array: ");
        printReverse(input, size, 0);
        System.out.println("Reverse printing of the Array using interesting way: ");
        printReverseInterestingWay(input, size, 0);
    }

    public static void printStraight(int[] input, int size, int i) {
        if(i < size){
            System.out.println(input[i]);
            printStraight(input, size, i+1);
        }
    }

    public static void printReverse(int[] input, int size, int i) {
        if(i < size){
            System.out.println(input[size-i-1]);
            printReverse(input, size, i+1);
        }
    }
    
    public static void printReverseInterestingWay(int[] input, int size, int i){
        if(i < size){
            printReverseInterestingWay(input, size, i+1);
            System.out.println(input[i]);
        }
    }
}

No comments:

Post a Comment

Hi Friends, Please leave your comments as they shall be greatest motivation , shall help me make corrections to my existing posts and will enable me to create better posts. :)