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?

john_science
  • 6,325
  • 6
  • 43
  • 60
PHZE OXIDE
  • 549
  • 3
  • 6
  • 8
  • 5
    Use a loop to swap each of the elements in the first half with the elements in the second half. – Peter Lawrey Oct 01 '12 at 18:23
  • If i used void that means i wont be able to use the return statement in this method right? – PHZE OXIDE Oct 01 '12 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. – Peter Lawrey Oct 01 '12 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]; }` – Letharion Oct 01 '12 at 18:41

15 Answers15

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]
Vikdor
  • 23,934
  • 10
  • 61
  • 84
69

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.

Elazar
  • 20,415
  • 4
  • 46
  • 67
Jordan Denison
  • 2,649
  • 14
  • 14
  • 21
    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 and not List (which is impossible anyway) so actually a List with exactly one entry which is reversed the same. This is true for all primitive arrays! – Dennis Ich Aug 26 '15 at 16:19
  • 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)); – Varun Chandran Jun 12 '19 at 06:21
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;
}
karmakaze
  • 34,689
  • 1
  • 30
  • 32
kanhai shah
  • 1,193
  • 10
  • 14
  • 2
    Isn't it worth to put `array.length / 2` part to outside before the for-loop? It will be recalculated every iteration, I believe. – Jin Kwon Mar 10 '14 at 03:24
  • @JinKwon I believe that the compiler will enhance it that way, you can try it out with javap – Zarathustra Mar 27 '14 at 18:49
  • @JinKwon To clarify this, I didn't mean javac, I was talking about the JIT compiler, the optimisation that happens at run time. – Zarathustra Mar 28 '14 at 10:24
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));
}
Luigi R. Viggiano
  • 8,659
  • 7
  • 53
  • 66
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

Mooncrater
  • 4,146
  • 4
  • 33
  • 62
The Badak
  • 2,010
  • 2
  • 16
  • 28
5

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

EFalco
  • 668
  • 1
  • 8
  • 11
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)

RNJ
  • 15,272
  • 18
  • 86
  • 131
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;
}
Mathias Bak
  • 4,687
  • 4
  • 32
  • 42
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;
}
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];
}
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;
}
Dharmesh Porwal
  • 1,406
  • 2
  • 12
  • 21
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;
        }
    }
David Soroko
  • 8,521
  • 2
  • 39
  • 51
  • 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 Jan 22 '17 at 16:41
  • 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). – geowar Jan 22 '17 at 16:42
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
}
iaL
  • 376
  • 9
  • 18
-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]);
1ac0
  • 2,875
  • 3
  • 33
  • 47
  • @Begueradj - it looks like an answer to me - not necessarily a good one, but it's an answer. – Krease Dec 04 '14 at 17:56
-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];


}
shayyy7
  • 93
  • 7