51

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?

4
  • 5
    Use a loop to swap each of the elements in the first half with the elements in the second half. Commented Oct 1, 2012 at 18:23
  • If i used void that means i wont be able to use the return statement in this method right? Commented Oct 1, 2012 at 18:27
  • That is true. You can either reserve the exist array which may or may not be returned. Or you can return a copy. Commented Oct 1, 2012 at 18:31
  • Based on the idea you already had, I would hazard a guess that you are very experienced in development, so I will point out an easy alternative. Just do what you want in a reversed for-loop, instead of actually reversing the array. for (int i = someArray.length - 1; i > 0; i--) { doStuff(someArray[i]); } reversedArray[j++] = firstArray[i]; } Commented Oct 1, 2012 at 18:41

15 Answers 15

71

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]
Sign up to request clarification or add additional context in comments.

4 Comments

Please see the edit to the answer.
Why instantiating a new ArrayList? Arrays.asList() already returns a List.
Thanks @cypressious, I was under the impression that Arrays.asList would return an unmodifiable list. Corrected that.
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.
68

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.

2 Comments

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!
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));
33

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;
}

3 Comments

Isn't it worth to put array.length / 2 part to outside before the for-loop? It will be recalculated every iteration, I believe.
@JinKwon I believe that the compiler will enhance it that way, you can try it out with javap
@JinKwon To clarify this, I didn't mean javac, I was talking about the JIT compiler, the optimisation that happens at run time.
12

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));
}

2 Comments

This was really helpful. I like the fact that you didn't change the original array, instead you returned a new array.
Doesn't work for array of Primitives though
12

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

Comments

5

You could use org.apache.commons.lang.ArrayUtils : ArrayUtils.reverse(array)

Comments

3

Or you could loop through it backeards

int[] firstArray = new int[]{1,2,3,4};
int[] reversedArray = new int[firstArray.length];
int j = 0;
for (int i = firstArray.length -1; i > 0; i--){
    reversedArray[j++] = firstArray[i];
}

(note: I have not compiled this but hopefully it is correct)

Comments

3

In place reversal with minimum amount of swaps.

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

Comments

2

I would do something like this:

public int[] reverse3(int[] nums) {
  int[] numsReturn = new int[nums.length()]; 
  int count = nums.length()-1;
  for(int num : nums) {
    numsReturn[count] = num;
    count--;
  }
  return numsReturn;
}

1 Comment

@RodrigoKossmann.. Or you can just use: - numsReturn[count--] = num
2

you messed up

int[] firstArray = new int[]{1,2,3,4};
int[] reversedArray = new int[firstArray.length];
int j = 0;
for (int i = firstArray.length -1; i >= 0; i--){
    reversedArray[j++] = firstArray[i];
}

Comments

2
 public void swap(int[] arr,int a,int b)
 {
    int temp=arr[a];
    arr[a]=arr[b];
    arr[b]=temp;        
}
public int[] reverseArray(int[] arr){
    int size=arr.length-1;

    for(int i=0;i<size;i++){

        swap(arr,i,size--); 

    }

    return arr;
}

Comments

2

The following will reverse in place the array between indexes i and j (to reverse the whole array call reverse(a, 0, a.length - 1))

    public void reverse(int[] a, int i , int j) {
        int ii =  i;
        int jj = j;

        while (ii < jj) {
            swap(ii, jj);
            ++ii;
            --jj;
        }
    }

2 Comments

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.
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).
2

In case you don't want to use a temporary variable, you can also do like this:

final int len = arr.length;
for (int i=0; i < (len/2); i++) {
    arr[i] += arr[len - 1 - i]; //  a = a+b
    arr[len - 1 - i] = arr[i] - arr[len - 1 - i];   //  b = a-b
    arr[i] -= arr[len - 1 - i]; //  a = a-b
}

Comments

-1

This code would help:

int [] a={1,2,3,4,5,6,7};
for(int i=a.length-1;i>=0;i--)
  System.out.println(a[i]);

1 Comment

@Begueradj - it looks like an answer to me - not necessarily a good one, but it's an answer.
-3

you can send the original array to a method for example:

after that you create a new array to hold the reversed elements

public static void reverse(int[] a){

int[] reversedArray = new int[a.length];

for(int i = 0 ; i<a.length; i++){
reversedArray[i] = a[a.length -1 -i];


}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.