Tuesday, October 27, 2015

Reverse int Array Iteratively in Java

A reverse of a primitive int array can be achieved by swapping elements from the start with the end iteratively.

If the swap operation of the primitive array elements starts from the index 0 then it is going to be enough to iterate till the half of the array.

Following is the in-place where there is no need to create-allocate a new array for reversing primitive array items implementation in Java.

package basics;

public class IterativeArrayReverse {

 private static void reverseArray( int[] inArr )
 {
     if ( inArr==null || inArr.length==0 )
         return ;
        
     int len = inArr.length;
     for( int i=0; i<len/2; i++ )
         swap(inArr, i, len-i-1);
 }
 
 private static void swap( int[] inArr, int i, int j )
 {
     int temp = inArr[i];
     inArr[i] = inArr[j];
     inArr[j] = temp;
 }
 
 public static void main(String[] args) {
  
     int[] arr = { 1,2,3,4,5,6 };
     System.out.println("Before Reverse");
     for( int i=0; i<arr.length; i++ )
         System.out.printf("%s ", arr[i]);  
  
     reverseArray( arr );
  
     System.out.println("\nAfter Reverse");
     for( int i=0; i<arr.length; i++ )
         System.out.printf("%s ", arr[i]);
  
     int[] arr2 = {4,3,6,2,7,8,9,5};
     System.out.println("\n\nBefore Reverse");
     for( int i=0; i<arr2.length; i++ )
         System.out.printf("%s ", arr2[i]);  
  
     reverseArray( arr2 );
  
     System.out.println("\nAfter Reverse");
     for( int i=0; i<arr2.length; i++ )
         System.out.printf("%s ", arr2[i]);
 }
}



Create a IterativeArrayReverse.java file in your workspace.

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

Before Reverse
1 2 3 4 5 6
After Reverse
6 5 4 3 2 1

Before Reverse
4 3 6 2 7 8 9 5
After Reverse
5 9 8 7 2 6 3 4

No comments:

Post a Comment