Reverse an array in Java recursively

  Write a program to reverse an array or string in java.👇👇👇

input - 

int arr[] = {2,3,4,5,6}

output - 

int arr[] = {6,5,4,3,2}

Here we have two approaches to reverse an array.

1- Iterative

2- Recursive

Recursive - 

In the recursive way first we have to initilize 

start = 0

end = n-1

swap arr[start] with arr[end]

Recursively call the method to reverse for the rest of the array.

*******************Code***************

package javaoneworld.learndsa.problems;

public class JavaOneWorldReverse {

    public static void main(String[] args) {

        int arrToReverse[] = {2,3,4,5,6,7,8,9};
        System.out.println("input array");
        printArray(arrToReverse,7);
        int reversedArray[] = reverseArrayRecursive(arrToReverse,0,7);
        System.out.println("output array");
        printArray(reversedArray,7);

    }

    

    private static int[] reverseArrayRecursive(int arr[],int start, int end){

        int temp;
        if(start>=end)
            return arr;
        else {

            temp = arr[start];
            arr[start] = arr[end];
            arr[end] = temp;
           return reverseArrayRecursive(arr,start+1,end-1);
        }
    }

    //print the array element
    private static void printArray(int arr[], int size){
        for(int i:arr){
            System.out.print(i+" ");
        }
        System.out.println();
    }
}
     
Time Complexity - O(n)

Thanks a bunch for being here.

No comments:

Post a Comment