Reversing an Array in Java

203,055

Solution 1

Collections.reverse() can do that job for you if you put your numbers in a List of Integers.

List<Integer> list = Arrays.asList(1, 4, 9, 16, 9, 7, 4, 9, 11);
System.out.println(list);
Collections.reverse(list);
System.out.println(list);

Output:

[1, 4, 9, 16, 9, 7, 4, 9, 11]
[11, 9, 4, 7, 9, 16, 9, 4, 1]

Solution 2

If you want to reverse the array in-place:

Collections.reverse(Arrays.asList(array));

It works since Arrays.asList returns a write-through proxy to the original array.

Solution 3

If you don't want to use Collections then you can do this:

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

Solution 4

I like to keep the original array and return a copy. This is a generic version:

public static <T> T[] reverse(T[] array) {
    T[] copy = array.clone();
    Collections.reverse(Arrays.asList(copy));
    return copy;
}

without keeping the original array:

public static <T> void reverse(T[] array) {
    Collections.reverse(Arrays.asList(array));
}

Solution 5

try this:

public int[] reverse3(int[] nums) {
    int[] reversed = new int[nums.length];
    for (int i=0; i<nums.length; i++) {
        reversed[i] = nums[nums.length - 1 - i];
    }
    return reversed;
}

My input was:

1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12

And the output I got:

12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1

Share:
203,055
PHZE OXIDE
Author by

PHZE OXIDE

Updated on April 23, 2020

Comments

  • PHZE OXIDE
    PHZE OXIDE about 4 years

    If I have an array like this:

    1 4 9 16 9 7 4 9 11 
    

    What is the best way to reverse the array so that it looks like this:

    11 9 4 7 9 16 9 4 1 
    

    I have the code below, but I feel it is a little tedious:

    public int[] reverse3(int[] nums) {
        return new int[] { nums[8], nums[7], nums[6], nums[5], num[4],
                           nums[3], nums[2], nums[1], nums[0] };
    }
    

    Is there a simpler way?

  • PHZE OXIDE
    PHZE OXIDE over 11 years
    Can you explain a little more thanks
  • Vikdor
    Vikdor over 11 years
    Please see the edit to the answer.
  • Rohit Jain
    Rohit Jain over 11 years
    @RodrigoKossmann.. Or you can just use: - numsReturn[count--] = num
  • Kirill Rakhman
    Kirill Rakhman over 11 years
    Why instantiating a new ArrayList? Arrays.asList() already returns a List.
  • Vikdor
    Vikdor over 11 years
    Thanks @cypressious, I was under the impression that Arrays.asList would return an unmodifiable list. Corrected that.
  • Jin Kwon
    Jin Kwon about 10 years
    Isn't it worth to put array.length / 2 part to outside before the for-loop? It will be recalculated every iteration, I believe.
  • Zarathustra
    Zarathustra about 10 years
    @JinKwon I believe that the compiler will enhance it that way, you can try it out with javap
  • Zarathustra
    Zarathustra about 10 years
    @JinKwon To clarify this, I didn't mean javac, I was talking about the JIT compiler, the optimisation that happens at run time.
  • Krease
    Krease over 9 years
    @Begueradj - it looks like an answer to me - not necessarily a good one, but it's an answer.
  • Dennis Ich
    Dennis Ich over 8 years
    Though an old answer it costed me some time to figure out... This does not work for the op as int[] is an object and Arrays.asList(array) will return List<int[]> and not List<int> (which is impossible anyway) so actually a List with exactly one entry which is reversed the same. This is true for all primitive arrays!
  • The Room
    The Room about 8 years
    This was really helpful. I like the fact that you didn't change the original array, instead you returned a new array.
  • geowar
    geowar over 7 years
    I like this answer because it avoids calling the .length method inside the loop and doesn't constantly calculate len - 1 - i; it works for any range of the array and uses swap instead of a temp variable. But there's no reason to use the duplicate variables (ii & jj); you can just use i & j directly. I'd swap(ii++, jj--) and avoid the extra lines.
  • geowar
    geowar over 7 years
    Note also that it only works if i < j; if you want it to always work you could assign ii = min(i,j) and jj = max(i,j).
  • Varun Chandran
    Varun Chandran almost 5 years
    public int decToBinary(int n) { // array to store binary number int[] binaryNum = new int[1000]; // counter for binary array int i = 0; while (n > 0) { // storing remainder in binary array binaryNum[i] = n % 2; n = n / 2; i++; } return Collections.reverse(Arrays.asList(binaryNum)); } ---------------- Gives an error --> error: incompatible types: void cannot be converted to int return Collections.reverse(Arrays.asList(binaryNum));
  • sunny_dev
    sunny_dev over 4 years
    Doesn't work for array of Primitives though
  • sunny_dev
    sunny_dev over 4 years
    Arrays.asList actually returns a Frozen list in the sense that you cannot add or remove any element from that newly created List. However you are allowed to do inplace element modifications.