Reverse an array in Java

 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

Iterative - 

In the Iterative way, we go from start to end one by one and swap arr[start] with arr[end],

and after that do start++ and end--;

we have to repeat this till start<end;


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");
        int reversedArray[] = reverseArray(arrToReverse,0,7);
        System.out.println("output array");


    /* Function to reverse arr[] from
    start to end*/
    private static int[] reverseArray(int arr[],int start,int end){
        int temp;
        while (start<end){
            temp = arr[start];
            arr[start] = arr[end];
            arr[end] = temp;
        return arr;

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

No comments:

Post a Comment