Thursday, October 15, 2015

Custom Reverse Primitive Integer Array in Java

In order to reverse an integer primitive array in java an in-place algorithm can be used.

General algorithm for reversing an integer array is :

1-) Traverse the array until the midpoint found in a loop construct
2-) Implement a swap algorithm to exchange values of the items in the array

Following is a utility method used to reverse an existing array in java.

package basics;

public class ArrayUtility {
 
 static int[] reverse( int[] input )
 {
     if( input==null || input.length==0 )
         return null;
        
     int N = input.length;
  
     for( int i=0; i<N/2; i++ )
     {
        int temp = input[i];
        input[i] = input[N-i-1];
        input[N-i-1] = temp;
     }
  
     return input;
 } 

 public static void main(String[] args) {
  
  int[] original = {22,55,66,11,32,56,67,89,95,10};
  
  System.out.print("Original Array = ");
  for( int i = 0; i<original.length; i++ )
   System.out.print( original[i]+" " );
  
  int[] reverseArray = reverse( original );
 
  System.out.print("\nReversed Array = ");
  for (int i = 0; i <reverseArray.length; i++)
   System.out.print(reverseArray[i]+" ");  
 }
 
}



Create a ArrayUtility.java file in your workspace.

When the main method inside the ArrayUtility class executed it is going to print :

Original Array = 22 55 66 11 32 56 67 89 95 10
Reversed Array = 10 95 89 67 56 32 11 66 55 22


No comments:

Post a Comment