Site icon

Reverse an integer array in java 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

Algorithm: reverse an integer array using recursive algorithm

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]
Exit mobile version