Reverse an integer array in java using iterative & recursive algorithm

  • Given an integer array in java.
  • Reverse input array using iterative & recursive algorithm.

Example to reverse an integer array using java

  1. Let input array is { 1, 2, 3, 4, 5 }
  2. Reverse input array is {5, 4, 3, 2, 1}

Algorithm: reverse an integer array using iterative algorithm

  • Initialize length = inputArray.length & half = length / 2.
  • Start traversing the input array till half length of array
    • Swap elements of array e.g. first element of array swapped with last element.
  • End traversing input array
  • Time complexity of algorithm is O (n).

Algorithm: reverse an integer array using recursive algorithm

  • Initialize low = 0 & high = inputArray.length – 1
  • Swap elements at low & high index
  • Increment low & decrement high index
  • Recursively call reverse method to reverse rest of elements of array.
  • Time complexity of algorithm is O (n).

Program – reverse an integer array in java using recursive & iterative method

package org.learn.arrays;

import java.util.Arrays;
import java.util.Collections;

public class reverseArray {

 public static void main(String[] args) {

  int[] inputArray = { 1, 2, 3, 4, 5 };
  System.out.println("1. Input Array is :" + Arrays.toString(inputArray));
  
  int[] copy = inputArray.clone();
  reverseArrayIterative(copy);
  String reverseArray = Arrays.toString(copy);
  System.out.println("2. Iterative method - reverse array :" + reverseArray);
  
  copy = inputArray.clone();
  reverseArrayRecursive(copy, 0 , copy.length - 1);
  reverseArray = Arrays.toString(copy);
  System.out.println("3. Recursive method - reverse array :" + reverseArray); 
  
 }

 private static void reverseArrayIterative(int[] inputArray) {
  int length = inputArray.length;
  int half = length / 2;

  for (int index = 0; index < half; index++) {
   int temp = inputArray[index];
   inputArray[index] = inputArray[length - 1 - index];
   inputArray[length - 1 - index] = temp;
  }
  
 }

 private static void reverseArrayRecursive(int[] inputArray, int low, int high) {

  if (high < low)
   return;

  int temp = inputArray[low];
  inputArray[low] = inputArray[high];
  inputArray[high ] = temp;
  reverseArrayRecursive(inputArray, low + 1, high - 1);
 }
}

Output – reverse an integer array in java using recursive & iterative method

1. Input Array is :[1, 2, 3, 4, 5]
2. Iterative method - reverse array :[5, 4, 3, 2, 1]
3. Recursive method - reverse array :[5, 4, 3, 2, 1]
Scroll to Top