How do I reverse an int array in Java?

Viewed 641272

I am trying to reverse an int array in Java.

This method does not reverse the array.

for(int i = 0; i < validData.length; i++)
{
    int temp = validData[i];
    validData[i] = validData[validData.length - i - 1];
    validData[validData.length - i - 1] = temp;
}

What is wrong with it?

47 Answers

To reverse an int array, you swap items up until you reach the midpoint, like this:

for(int i = 0; i < validData.length / 2; i++)
{
    int temp = validData[i];
    validData[i] = validData[validData.length - i - 1];
    validData[validData.length - i - 1] = temp;
}

The way you are doing it, you swap each element twice, so the result is the same as the initial list.

With Commons.Lang, you could simply use

ArrayUtils.reverse(int[] array)

Most of the time, it's quicker and more bug-safe to stick with easily available libraries already unit-tested and user-tested when they take care of your problem.

public class ArrayHandle {
    public static Object[] reverse(Object[] arr) {
        List<Object> list = Arrays.asList(arr);
        Collections.reverse(list);
        return list.toArray();
    }
}

In case of Java 8 we can also use IntStream to reverse the array of integers as:

int[] sample = new int[]{1,2,3,4,5};
int size = sample.length;
int[] reverseSample = IntStream.range(0,size).map(i -> sample[size-i-1])
                      .toArray(); //Output: [5, 4, 3, 2, 1]

This will help you

int a[] = {1,2,3,4,5};
for (int k = 0; k < a.length/2; k++) {
    int temp = a[k];
    a[k] = a[a.length-(1+k)];
    a[a.length-(1+k)] = temp;
}

Your program will work for only length = 0, 1. You can try :

int i = 0, j = validData.length-1 ; 
while(i < j)
{
     swap(validData, i++, j--);  // code for swap not shown, but easy enough
}

There are two ways to have a solution for the problem:

1. Reverse an array in space.

Step 1. Swap the elements at the start and the end index.

Step 2. Increment the start index decrement the end index.

Step 3. Iterate Step 1 and Step 2 till start index < end index

For this, the time complexity will be O(n) and the space complexity will be O(1)

Sample code for reversing an array in space is like:

public static int[] reverseAnArrayInSpace(int[] array) {
    int startIndex = 0;
    int endIndex = array.length - 1;
    while(startIndex < endIndex) {
        int temp = array[endIndex];
        array[endIndex] = array[startIndex];
        array[startIndex] = temp;
        startIndex++;
        endIndex--;
    }
    return array;
}

2. Reverse an array using an auxiliary array.

Step 1. Create a new array of size equal to the given array.

Step 2. Insert elements to the new array starting from the start index, from the given array starting from end index.

For this, the time complexity will be O(n) and the space complexity will be O(n)

Sample code for reversing an array with auxiliary array is like:

public static int[] reverseAnArrayWithAuxiliaryArray(int[] array) {
    int[] reversedArray = new int[array.length];
    for(int index = 0; index < array.length; index++) {
        reversedArray[index] = array[array.length - index -1]; 
    }
    return reversedArray;
}

Also, we can use the Collections API from Java to do this.

The Collections API internally uses the same reverse in space approach.

Sample code for using the Collections API is like:

public static Integer[] reverseAnArrayWithCollections(Integer[] array) {
    List<Integer> arrayList = Arrays.asList(array);
    Collections.reverse(arrayList);
    return arrayList.toArray(array);
}

There are some great answers above, but this is how I did it:

public static int[] test(int[] arr) {

    int[] output = arr.clone();
    for (int i = arr.length - 1; i > -1; i--) {
        output[i] = arr[arr.length - i - 1];
    }
    return output;
}

It is most efficient to simply iterate the array backwards.

I'm not sure if Aaron's solution does this vi this call Collections.reverse(list); Does anyone know?

Solution with o(n) time complexity and o(1) space complexity.

void reverse(int[] array) {
    int start = 0;
    int end = array.length - 1;
    while (start < end) {
        int temp = array[start];
        array[start] = array[end];
        array[end] = temp;
        start++;
        end--;
    }
}

2 ways to reverse an Array .

  1. Using For loop and swap the elements till the mid point with time complexity of O(n/2).

    private static void reverseArray() {
    int[] array = new int[] { 1, 2, 3, 4, 5, 6 };
    
    for (int i = 0; i < array.length / 2; i++) {
        int temp = array[i];
        int index = array.length - i - 1;
        array[i] = array[index];
        array[index] = temp;
    }
    System.out.println(Arrays.toString(array));
    

    }

  2. Using built in function (Collections.reverse())

    private static void reverseArrayUsingBuiltInFun() {
    int[] array = new int[] { 1, 2, 3, 4, 5, 6 };
    
    Collections.reverse(Ints.asList(array));
    System.out.println(Arrays.toString(array));
    

    }

    Output : [6, 5, 4, 3, 2, 1]

    public static void main(String args[])    {
        int [] arr = {10, 20, 30, 40, 50}; 
        reverse(arr, arr.length);
    }

    private static void reverse(int[] arr,    int length)    {

        for(int i=length;i>0;i--)    { 
            System.out.println(arr[i-1]); 
        }
    }
static int[] reverseArray(int[] a) {
     int ret[] = new int[a.length];
     for(int i=0, j=a.length-1; i<a.length && j>=0; i++, j--)
         ret[i] = a[j];
     return ret;
}
 public static int[] reverse(int[] array) {

    int j = array.length-1;
    // swap the values at the left and right indices //////
        for(int i=0; i<=j; i++)
        {
             int temp = array[i];
                array[i] = array[j];
                array[j] = temp;
           j--;
        }

         return array;
    }

      public static void main(String []args){
        int[] data = {1,2,3,4,5,6,7,8,9};
        reverse(data);

    }

A implementation using generics for arrays of non primitive types.

    //Reverse and get new Array -preferred
    public static final <T> T[] reverse(final T[] array) {
        final int len = array.length;
        final T[] reverse = (T[]) Array.newInstance(array.getClass().getComponentType(), len);
        for (int i = 0; i < len; i++) {
            reverse[i] = array[len-(i+1)];
        }
        return reverse;
    }
    
    //Reverse existing array - don't have to return it
    public static final <T> T[] reverseExisting(final T[] array) {
        final int len = array.length;
        for (int i = 0; i < len/2; i++) {
            final T temp = array[i];
            array[i] = array[len-(i+1)];
            array[len-(i+1)] = temp;
        }
        return array;
    }

enter image description here

a piece of cake. i did it for string but, it's not much different

A short way to reverse without additional libraries, imports, or static references.

int[] a = {1,2,3,4,5,6,7,23,9}, b; //compound declaration
var j = a.length;
b = new int[j];
for (var i : a)
    b[--j] = i; //--j so you don't have to subtract 1 from j. Otherwise you would get ArrayIndexOutOfBoundsException;
System.out.println(Arrays.toString(b));

Of course if you actually need a to be the reversed array just use

a = b; //after the loop

Here is a condensed version:

My solution creates a new array reversed With each iteration of i the for loop inserts the last index [array.length - 1] into the current index [i] Then continues the same process by subtracting the current iteration array[(array.length - 1) - i] from the last index and inserting the element into the next index of the reverse array!

private static void reverse(int[] array) {
    int[] reversed = new int[array.length];

    for (int i = 0; i < array.length; i++) {
        reversed[i] = array[(array.length - 1) - i];
    }
    System.out.println(Arrays.toString(reversed));
}

Just for the sake of it. People often do only need a 'view' on an array or list in reversed order instead of a completely do not need a reversed array when working with streams and collections but a 'reversed' view on the original array/collection. , it is best to create a toolkit that has a reverse view on a list / array.

So create your Iterator implementation that takes an array or list and provide the input.

/// Reverse Iterator
public class ReverseIterator<T> implements Iterator<T> {
  private int index;
  private final List<T> list;
  public ReverseIterator(List<T> list) {
     this.list = list;
     this.index = list.size() - 1;
  }
  public boolean hasNext() {
    return index >= 0 ? true : false;
  }
  public T next() {
    if(index >= 0) 
      return list.get(index--);
    else 
      throw new NoSuchElementException();
  }
}

An implementation for the array situation is quite similar. Of cause an iterator can be source for a stream or a collection as well.

So not always it is best to create a new array just to provide a reverse view when all you want to do is iterating over the array / list or feed it into a stream or a new collection / array.

This has 2 solution

  1. Loop

  2. Recursion

    public class _1_ReverseArray {

     public static void main(String[] args) {
         int array[] = {2, 3, 1, 4, 9};
         //reverseArray(array, 0, array.length - 1);
         reverseArrayWhileLoop(array, 0, array.length - 1);
         printArray(array);
     }
    
     private static void printArray(int[] array) {
         for (int a : array) {
             System.out.println(a);
         }
     }
    
     private static void reverseArray(int[] array, int start, int end) {
         if (start > end) {
             return;
         } else {
             int temp;
             temp = array[start];
             array[start] = array[end];
             array[end] = temp;
             reverseArray(array, start + 1, end - 1);
         }
     }
    
     private static void reverseArrayWhileLoop(int[] array, int start, int end) {
         while (start < end) {
             int temp;
             temp = array[start];
             array[start] = array[end];
             array[end] = temp;
             start++;
             end--;
         }
     }
    

    }

Simple way to do this:

    for(int i=queue.length-1;i>=0;i--){
                System.out.print(queue[i] + "  ");
    }
   import java.util.Scanner;
class ReverseArray 
{
    public static void main(String[] args) 
    {
        int[] arra = new int[10];
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter Array Elements : ");
        for(int i = 0 ; i <arra.length;i++)
        {
            arra[i] = sc.nextInt();
        }

        System.out.println("Printing  Array : ");
        for(int i = 0; i <arra.length;i++)
        {
            System.out.print(arra[i] + " ");
        }

        System.out.println();
        System.out.println("Printing  Reverse Array : ");
        for(int i = arra.length-1; i >=0;i--)
        {
            System.out.print(arra[i] + " ");
        }
    }
}
Related