Tuesday, September 8, 2015

Reverse Integer Array Recursively in Java

Recursion can be used to reverse an integer array without allocating a new array.

This method is more space efficient than the solution which creates a new array to hold the reversed one.

By starting from the specific start index to end index inclusively, following method enables to reverse items at specific array index recursively.

public class ReverseArray {

 public static void reverseArray( int[] data, int low, int high )
 {
  if( low<high )
  {
   int temp = data[low];
   data[low] = data[high];
   data[high] = temp;
   reverseArray(data, low+1, high-1);   
  }  
 }
 
 public static void main(String[] args) {
  
  int[] arr = {4,3,6,2,7,8,9,5};
  
  for (int i = 0; i < arr.length; i++) {
   
   System.out.print(arr[i]+" ");   
  }
  
  System.out.println();
  
  reverseArray(arr, 1, 3);
  
  for (int i = 0; i < arr.length; i++) {
   
   System.out.print(arr[i]+" ");   
  }  
  
 }
}



Sample input and output arrays can be used :












Reference :  http://www.amazon.com/Data-Structures-Algorithms-Java-Edition-ebook/dp/B00JDRQF8C


No comments:

Post a Comment