291

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?

Patrick Parker
  • 4,863
  • 4
  • 19
  • 51
MichaelScott
  • 2,937
  • 2
  • 16
  • 4

47 Answers47

340

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.

3lectrologos
  • 9,469
  • 4
  • 39
  • 46
  • 1
    And I would like to put `validData.length / 2` part to the outside of the for-loop. – Jin Kwon Mar 10 '14 at 03:28
  • 10
    @Jin I wouldn't. It only obfuscates the meaning, and I bet the optimizing compiler would do it for you anyway. Regardless, there's no point micro-optimizing until you have clear evidence from profiling that it is necessary/helpful. – Nicu Stiurca Apr 07 '14 at 18:11
  • 9
    @JinKwon That would be sort of like doing `validData.length >> 1`. That is equivalent and faster, but it confuses many programmers and any good compiler will automatically do that. – Justin Apr 07 '14 at 18:54
  • 2
    You should only do this calculation once `validData.length - i - 1` and save it to a variable. –  May 19 '15 at 23:59
  • Can any one suggest a reversal with out temp variable !! – sg28 Jul 11 '18 at 06:23
  • @sg28 that was already provided by [AbsoluteBlue here](https://stackoverflow.com/a/7395428/7098259). Or you could use recursion. – Patrick Parker Dec 01 '18 at 03:49
  • 1
    @sg28 What's the point of eliminating the temporary variable? – Stefan Reich Mar 25 '22 at 19:39
329

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.

Manur
  • 8,436
  • 2
  • 27
  • 29
84
Collections.reverse(Arrays.asList(yourArray));

java.util.Collections.reverse() can reverse java.util.Lists and java.util.Arrays.asList() returns a list that wraps the the specific array you pass to it, therefore yourArray is reversed after the invocation of Collections.reverse().

The cost is just the creation of one List-object and no additional libraries are required.

A similar solution has been presented in the answer of Tarik and their commentors, but I think this answer would be more concise and more easily parsable.

escitalopram
  • 3,750
  • 2
  • 23
  • 24
  • 38
    For arrays of objects, this is a good solution. But it doesn't work for arrays of primitives. E. g. passing an `int[]` to `asList(...)` will not return a `List`, but a `List`, containing one element. There is AFAICS no simple built-in way to convert an `int[]` to an `Integer[]`. – Martin Rust Sep 22 '16 at 07:14
  • 9
    This wont work with primitive arrays... collections dosnt return a value so now you have a useless array as a list in memory – NightSkyCode Oct 23 '16 at 20:08
  • 1
    @MartinRust Java 8+: `Arrays.stream(arr).boxed().collect(Collectors.toList())` or `Arrays.stream(arr).boxed().toArray(Integer[]::new)` – Simon Forsberg Jun 10 '20 at 09:03
  • 1
    @KingLogic Well, it's a one-liner and the prettiest thing I could come up with. Feel free to suggest something better (that does not rely upon a library). – Simon Forsberg Jul 07 '21 at 11:25
61
public class ArrayHandle {
    public static Object[] reverse(Object[] arr) {
        List<Object> list = Arrays.asList(arr);
        Collections.reverse(list);
        return list.toArray();
    }
}
Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
Tarik
  • 79,711
  • 83
  • 236
  • 349
  • 11
    Of course it will. A list can only hold Objects, not primitives, so all the primitives (`int`s in this case) are wrapped in to their respective wrappers (`Integer`s in this case) and put in the list. You see, `Integer`s are objects. @Tom – 11684 Dec 03 '12 at 17:03
  • 8
    Watch out: If I'm not wrong the original array is modified. To make it clear you may want to just not return anything. – Andrea Zilio Feb 05 '13 at 19:25
  • 1
    how would you convert Object[] array that it returns back to int[] array??? The OP asked the question for array of ints so could you please the give the code that works for array of ints out of the box? Thanks. – vincent mathew May 20 '13 at 05:30
  • Doen't matter! What matters is: no loops, no dependencies. Therefore the best answer. – filip Aug 02 '14 at 20:48
  • 3
    @11684 Yes, generic lists can only hold Objects. But the method excepts an array. Arrays can hold primitives. Therefore `int[]` is different from `Integer[]`. Try it: `Integer[] array = new int[5]`. You'll get a compile error. This is why the Java `Arrays` class defines a bunch of methods for working with primitive arrays. Trying to pass an `int[]` to the above method will result in something like `The method reverse(Object[]) in the type MakeSimple is not applicable for the arguments (int[])`. @Filip - an in-place algorithm uses less memory and runs faster. – Brian McCutchon Oct 18 '14 at 16:20
  • 3
    @Andrea Actually, it isn't. The list returned by `Arrays.asList()` doesn't reference the original array, nor does the array returned. That's one of the problems with this method: it uses triple the memory and does triple the work as an in-place algorithm. – Brian McCutchon Oct 18 '14 at 16:25
  • 1
    Looks like I was wrong about `Arrays.asList()`: actually, it does reference the original array. So this only uses twice the memory and does twice the work (since `List.toArray` generates a completely new array). A good non-in-place algorithm would still use twice the memory, but do the same amount of work as the in-place method. @Andrea You're right. Looks like `Collections.reverse(Arrays.asList(array))` is a valid way to reverse an array. Unfortunately, this doesn't work for primitives. – Brian McCutchon Oct 18 '14 at 16:35
  • 4
    This method itself might work, but one simply cannot pass an `int[]` as an argument to this method (*"incompatible types: int[] cannot be converted to Object[]"*). – MC Emperor Nov 17 '17 at 12:41
  • For ints: public static Object[] reverse(Integer[] arr) { List list = Arrays.asList(arr); Collections.reverse(list); return list.toArray(); in your main: (example) Integer[] numbers= {1,2,8,3}; Object[]number=(Integer[]) reverse(numbers); – Rim Nov 19 '18 at 00:22
45

I think it's a little bit easier to follow the logic of the algorithm if you declare explicit variables to keep track of the indices that you're swapping at each iteration of the loop.

public static void reverse(int[] data) {
    for (int left = 0, right = data.length - 1; left < right; left++, right--) {
        // swap the values at the left and right indices
        int temp = data[left];
        data[left]  = data[right];
        data[right] = temp;
    }
}

I also think it's more readable to do this in a while loop.

public static void reverse(int[] data) {
    int left = 0;
    int right = data.length - 1;

    while( left < right ) {
        // swap the values at the left and right indices
        int temp = data[left];
        data[left] = data[right];
        data[right] = temp;

        // move the left and right index pointers in toward the center
        left++;
        right--;
    }
}
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
  • old school swap looks more easy but yes when involving array index values left,right,... will be helpful for debugging if any – Srinath Ganesh Jul 25 '14 at 01:34
  • You could also add 'public static void swap(int[] data, int index1, int index2) { ... }' and use that from 'reverse' like this: swap(data, left, right). – pm_ Dec 10 '15 at 15:29
17

Use a stream to reverse

There are already a lot of answers here, mostly focused on modifying the array in-place. But for the sake of completeness, here is another approach using Java streams to preserve the original array and create a new reversed array:

int[] a = {8, 6, 7, 5, 3, 0, 9};
int[] b = IntStream.rangeClosed(1, a.length).map(i -> a[a.length-i]).toArray();
ZhekaKozlov
  • 36,558
  • 20
  • 126
  • 155
Patrick Parker
  • 4,863
  • 4
  • 19
  • 51
14

Guava

Using the Google Guava library:

Collections.reverse(Ints.asList(array));
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
ZhekaKozlov
  • 36,558
  • 20
  • 126
  • 155
  • 5
    This is brilliant! Short and effective. Like all `asList` methods, it creates a **view** that writes directly through to the backing (primitive) array. I think the down-voter here mistakenly thought that this returned a boxed list or something. – Luke Usherwood Dec 29 '16 at 09:33
  • @LukeUsherwood presumably there will still be some overhead from boxing and unboxing when calling get and set on each element. But I agree with you that this is a brilliant solution. – Patrick Parker Feb 13 '17 at 09:47
  • Indeed, that's worth being aware of. I don't think it would be a big deal in the majority of code I personally work with - our 'hot' areas are well defined, the rest is 'glue code' of sorts. At the same time I am concious that memory churn also creates an additional "hidden" cost that profilers don't attribute to the actual function. – Luke Usherwood Feb 13 '17 at 13:35
  • @LukeUsherwood it still does return a boxed list instead of a prim array – AnthonyJClink Oct 01 '18 at 20:07
  • 2
    @AnthonyJClink Not sure what "it" refers to, but the JDK utility `Collections.reverse` is a void method. This operates in-place on a Guava internal class which wraps an `int[]` (Since it never stores a list of boxed `Integer`s I wouldn't call the class a "boxed list", but rather a "List view of an array"). But yes it operates via an interface passing `Integer` objects, so this would create a lot of temporary object churn and boxing as mentioned. Try an `IntStream` or a primitive-collection library for where performance matters. (Trove, Koloboke, Eclipse Collections, ...) – Luke Usherwood Oct 02 '18 at 14:15
  • @LukeUsherwood as per the documentation for Ints. : Methods Modifier and Type Method and Description static List asList(int... backingArray) Returns a fixed-size list backed by the specified array, similar to Arrays.asList(Object[]). Hence... it is a boxed list. – AnthonyJClink Oct 02 '18 at 20:53
  • @AnthonyJClink ok sounds like we agree about how it works. – Luke Usherwood Oct 03 '18 at 16:48
  • What's `Ints` ? – Abhijit Sarkar Apr 22 '19 at 04:28
  • @AbhijitSarkar [Ints](https://google.github.io/guava/releases/27.1-jre/api/docs/com/google/common/primitives/Ints.html) – ZhekaKozlov Apr 22 '19 at 04:53
  • You conveniently assumed OP is using Guava. Java sucks in this regard, that there are no library methods to operate on primitive arrays, but that doesn't mean people are off to using another library. I must have missed the "With Guava:" disclaimer. – Abhijit Sarkar Apr 22 '19 at 05:28
13

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]
Laser Infinite
  • 253
  • 1
  • 15
akhil_mittal
  • 23,309
  • 7
  • 96
  • 95
10
for(int i=validData.length-1; i>=0; i--){
  System.out.println(validData[i]);
 }
Deepak Singh
  • 460
  • 2
  • 7
  • 19
  • 1
    Unfortunately, this is the most clean answer available here, because every developer will know how to do it and it doesn't require any extended package installs. – HoldOffHunger Jun 16 '17 at 00:15
  • 3
    This is good for getting the values of the array, but if you really want to reverse the array, you would have to create a new one using this method => the other ones would be more efficient. – Cactusroot May 24 '21 at 10:20
9

Simple for loop!

for (int start = 0, end = array.length - 1; start <= end; start++, end--) {
    int aux = array[start];
    array[start]=array[end];
    array[end]=aux;
}
ThisClark
  • 14,352
  • 10
  • 69
  • 100
Apetrei Ionut
  • 293
  • 4
  • 12
6

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;
}
Radiodef
  • 37,180
  • 14
  • 90
  • 125
Krishna Kumar Chourasiya
  • 2,030
  • 3
  • 20
  • 23
6

This is how I would personally solve it. The reason behind creating the parametrized method is to allow any array to be sorted... not just your integers.

I hope you glean something from it.

@Test
public void reverseTest(){
   Integer[] ints = { 1, 2, 3, 4 };
   Integer[] reversedInts = reverse(ints);

   assert ints[0].equals(reversedInts[3]);
   assert ints[1].equals(reversedInts[2]);
   assert ints[2].equals(reversedInts[1]);
   assert ints[3].equals(reversedInts[0]);

   reverseInPlace(reversedInts);
   assert ints[0].equals(reversedInts[0]);
}

@SuppressWarnings("unchecked")
private static <T> T[] reverse(T[] array) {
    if (array == null) {
        return (T[]) new ArrayList<T>().toArray();
    }
    List<T> copyOfArray = Arrays.asList(Arrays.copyOf(array, array.length));
    Collections.reverse(copyOfArray);
    return copyOfArray.toArray(array);
}

private static <T> T[] reverseInPlace(T[] array) {
    if(array == null) {
        // didn't want two unchecked suppressions
        return reverse(array);
    }

    Collections.reverse(Arrays.asList(array));
    return array;
}
AnthonyJClink
  • 1,008
  • 2
  • 11
  • 32
  • 2
    Doesn't solve the original problem using primatives. – Melinda Green Feb 12 '15 at 02:19
  • There are many ways to convert prims to objects. I always recommend avoiding prims wherever possible in java and I also believe that it should be encouraged. – AnthonyJClink Feb 12 '15 at 18:04
  • Converting an array of primitives of unknown length into an array might be a very bad idea, especially if done without realizing it. Java is not Smalltalk. Primitives are part of the language and have their place. It doesn't matter if we don't like them, we must accept them, and use them where appropriate. – Melinda Green Feb 13 '15 at 00:33
  • 2
    You actually don't need to copy the array, just `Collections.reverse(asList(arraytoReverse)); return arrayToReverse;`. `asList` is just a wrapper around the array, so the original array is reversed. – Radiodef Jun 12 '15 at 03:03
  • Your `return (T[]) new ArrayList().toArray();` will actually return an empty `Object[]`, not whatever type the parameter was. – Paŭlo Ebermann Jul 28 '23 at 15:31
6

If working with data that is more primitive (i.e. char, byte, int, etc) then you can do some fun XOR operations.

public static void reverseArray4(int[] array) {
    int len = array.length;
    for (int i = 0; i < len/2; i++) {
        array[i] = array[i] ^ array[len - i  - 1];
        array[len - i  - 1] = array[i] ^ array[len - i  - 1];
        array[i] = array[i] ^ array[len - i  - 1];
    }
}
AbsoluteBlue
  • 69
  • 1
  • 1
4

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
}
fastcodejava
  • 39,895
  • 28
  • 133
  • 186
  • 3
    Perhaps you meant swap as pseudo code for an inline swap rather than a method call, but if not that won't work. Java passes by reference so it is not possible to write a swap method for variables. – Dean Povey Jan 26 '10 at 07:27
  • I meant whatever way you can get v[i] & v[j] to swap. I am aware how method calls work in java. For method, you can do something like swap(v, i++, j--); – fastcodejava Jan 26 '10 at 07:39
  • 1
    Dean, the array validData is an object, passed by reference, so the swap() method will work perfectly. – Gaël Oberson Aug 21 '15 at 11:37
4

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);
}
Karan Khanna
  • 1,947
  • 3
  • 21
  • 49
4

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;
}
סטנלי גרונן
  • 2,917
  • 23
  • 46
  • 68
Ahmad Dalao
  • 1,968
  • 1
  • 8
  • 14
3

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?

Nick Strupat
  • 4,928
  • 4
  • 44
  • 56
  • Iterating backwards over the array requires a new array. I like the solution posted above that does the inline reversing without creating a new array. – mmcdole Jan 26 '10 at 06:27
  • 1
    @Simucal why create a new array? Just iterate it backwards. – Hakanai Oct 22 '15 at 00:23
3
public void getDSCSort(int[] data){
        for (int left = 0, right = data.length - 1; left < right; left++, right--){
            // swap the values at the left and right indices
            int temp = data[left];
            data[left]  = data[right];
            data[right] = temp;
        }
    }
subinksoman
  • 426
  • 4
  • 20
3

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--;
    }
}
user11016
  • 171
  • 7
  • Just FYI, this can be simplified into a complex for loop: `for (int start = 0, end = array.length - 1; start < end; start++, end--) { ... }`. – Tim Cooke Oct 25 '17 at 05:34
2

Wouldn't doing it this way be much more unlikely for mistakes?

    int[] intArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int[] temp = new int[intArray.length];
    for(int i = intArray.length - 1; i > -1; i --){
            temp[intArray.length - i -1] = intArray[i];
    }
    intArray = temp;
Moddl
  • 360
  • 3
  • 13
2

Using the XOR solution to avoid the temp variable your code should look like

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

See this link for a better explanation:

http://betterexplained.com/articles/swap-two-variables-using-xor/

vikarjramun
  • 1,042
  • 12
  • 30
2

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]

2
    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]); 
        }
    }
2
public void display(){
  String x[]=new String [5];
  for(int i = 4 ; i > = 0 ; i-- ){//runs backwards

    //i is the nums running backwards therefore its printing from       
    //highest element to the lowest(ie the back of the array to the front) as i decrements

    System.out.println(x[i]);
  }
}
Udo Held
  • 12,314
  • 11
  • 67
  • 93
  • 1
    yes i have tried the same and clear code along with output is int[] a = {1,3,5,2,6,7}; for(int i = a.length-1;i>=0;i--) {System.out.print(a[i]+" ");}` it will reverse the array from last index to first index – Rocket_03 Aug 22 '18 at 10:24
1

below is the complete program to run in your machine.

public class ReverseArray {
    public static void main(String[] args) {
        int arr[] = new int[] { 10,20,30,50,70 };
        System.out.println("reversing an array:");
        for(int i = 0; i < arr.length / 2; i++){
            int temp = arr[i];
            arr[i] = arr[arr.length - i - 1];
            arr[arr.length - i - 1] = temp;
        }
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }   
    }
}

For programs on matrix using arrays this will be the good source.Go through the link.

Mdhar9e
  • 1,376
  • 4
  • 23
  • 46
1
private static int[] reverse(int[] array){
    int[] reversedArray = new int[array.length];
    for(int i = 0; i < array.length; i++){
        reversedArray[i] = array[array.length - i - 1];
    }
    return reversedArray;
} 
Radiodef
  • 37,180
  • 14
  • 90
  • 125
Stuart Clark
  • 611
  • 8
  • 13
1

Here is a simple implementation, to reverse array of any type, plus full/partial support.

import java.util.logging.Logger;

public final class ArrayReverser {
 private static final Logger LOGGER = Logger.getLogger(ArrayReverser.class.getName());

 private ArrayReverser () {

 }

 public static <T> void reverse(T[] seed) {
    reverse(seed, 0, seed.length);
 }

 public static <T> void reverse(T[] seed, int startIndexInclusive, int endIndexExclusive) {
    if (seed == null || seed.length == 0) {
        LOGGER.warning("Nothing to rotate");
    }
    int start = startIndexInclusive < 0 ? 0 : startIndexInclusive;
    int end = Math.min(seed.length, endIndexExclusive) - 1;
    while (start < end) {
        swap(seed, start, end);
        start++;
        end--;
    }
}

 private static <T> void swap(T[] seed, int start, int end) {
    T temp =  seed[start];
    seed[start] = seed[end];
    seed[end] = temp;
 }  

}

Here is the corresponding Unit Test

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

import org.junit.Before;
import org.junit.Test;

public class ArrayReverserTest {
private Integer[] seed;

@Before
public void doBeforeEachTestCase() {
    this.seed = new Integer[]{1,2,3,4,5,6,7,8};
}

@Test
public void wholeArrayReverse() {
    ArrayReverser.<Integer>reverse(seed);
    assertThat(seed[0], is(8));
}

 @Test
 public void partialArrayReverse() {
    ArrayReverser.<Integer>reverse(seed, 1, 5);
    assertThat(seed[1], is(5));
 }
}
craftsmannadeem
  • 2,665
  • 26
  • 22
1

Here is what I've come up with:

// solution 1 - boiler plated 
Integer[] original = {100, 200, 300, 400};
Integer[] reverse = new Integer[original.length];

int lastIdx = original.length -1;
int startIdx = 0;

for (int endIdx = lastIdx; endIdx >= 0; endIdx--, startIdx++)
   reverse[startIdx] = original[endIdx];

System.out.printf("reverse form: %s", Arrays.toString(reverse));

// solution 2 - abstracted 
// convert to list then use Collections static reverse()
List<Integer> l = Arrays.asList(original);
Collections.reverse(l);
System.out.printf("reverse form: %s", l);
Simple-Solution
  • 4,209
  • 12
  • 47
  • 66
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;
}
Z A Abbasi
  • 129
  • 1
  • 8
1
 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);

    }
roshan posakya
  • 1,010
  • 10
  • 14
1

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;
    }
krishna T
  • 425
  • 4
  • 14
0

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
Bwizz
  • 81
  • 6
0

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

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.

Martin Kersten
  • 5,127
  • 8
  • 46
  • 77
0

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

    }

Aalishan Ansari
  • 641
  • 6
  • 8
-1
public class TryReverse {
    public static void main(String[] args) {        
        int [] array = {2,3,4,5,6,7,8,9};       
        reverse(array);
        for(int i=0; i<array.length; ++i)
            System.out.print(array[i] + " ");
    }
    public static void reverse (int [] array){
        for(int start=0, end=array.length-1; start<=end; start++, end--){
            int aux = array[start];
            array[start]=array[end];
            array[end]=aux;
        }
    }
}
Apetrei Ionut
  • 293
  • 4
  • 12
-1

Try this program in JAVA :-

import java.util.Scanner;

public class Rev_one_D {

    static int row;

    static int[] trans_arr = new int[row];

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        row = n;

        int[] arr = new int[row];
        for (int i = 0; i < row; i++) {

            arr[i] = sc.nextInt();
            System.out.print(arr[i] + " ");

            System.out.println();
        }

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

        }

        for (int i = 0; i < row; i++) {
            System.out.print(arr[i] + " ");
            System.out.println();
        }
    }
}
Nikhil Kumar
  • 2,618
  • 3
  • 21
  • 24
-1

Here's a simple an quick solution. Hope it helps!.

public int[] reverse(int[] arr) {
    for(int i = arr.length; i > 0 ; i--){
        System.out.print(arr[i-1] + " ");
    }
    return arr;
}
HenryDev
  • 4,685
  • 5
  • 27
  • 64
-1

Another way to reverse array

public static int []reversing(int[] array){
    int arraysize = array.length;
    int[] reverse = new int [arraysize+1];
    for(int i=1; i <= arraysize ; i++){
        int dec= arraysize -i;
        reverse[i] = array[dec];
    }
    return reverse;
}
marela
  • 1
  • 1
-1

As I intended to keep my original Array as it was, I solved this problem in the following manner:

List<Integer> normalArray= new ArrayList<>();
List<Integer> reversedArray = new ArrayList<>();

// Fill up array here

for (int i = 1; i <= normalArray.size(); i++) {
  reversedArray .add(normalArray.get(normalArray.size()-i));
}

So basically loop through the initial array and add all the values in reversed order to the new (reversed) array. The type of the list can be anything. I work my way through this code multiple times, this causes some of the other solutions not to work.

Mathieu Brouwers
  • 564
  • 7
  • 19
-1
   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] + " ");
        }
    }
}
jagdish khetre
  • 1,381
  • 2
  • 8
  • 15
-1

enter image description here

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

Community
  • 1
  • 1
Nasib
  • 1,173
  • 1
  • 13
  • 23
-1

Simple way to do this:

    for(int i=queue.length-1;i>=0;i--){
                System.out.print(queue[i] + "  ");
    }
Maninder
  • 1,539
  • 1
  • 10
  • 12
-1
public static void main (String args[]){

    //create  array
    String[] stuff ={"eggs","lasers","hats","pie","apples"};

    //print out  array
    for(String x :stuff)
        System.out.printf("%s ", x);
            System.out.println();

            //print out array in reverse order
            for(int i=stuff.length-1; i >= 0; i--)
                System.out.printf("%s ",stuff[i]);  

}
Kane
  • 7
  • 1
-2

You can use this

public final class ReverseComparator<T extends Comparable<T>> implements  Comparator<T> {
  @Override
  public int compare(T o1, T o2) {      
    return o2.compareTo(o1);
  }
}

An simply

Integer[] a = {1,6,23,4,6,8,2}
Arrays.sort(a, new ReverseComparator<Integer>());
FrederikH
  • 139
  • 2
  • 7
  • Even more simpel from java 1.7+ 'code' Integer[] a = new Integer[]{1,6,23,4,6,8,2} Arrays.sort(a, java.util.Collections.reverseOrder()); – FrederikH Sep 24 '15 at 17:34
-2

Try this code:

    int arr[] = new int[]{1,2,3,4,5,6,7};
    for(int i=0;i<arr.length/2;i++){
        int temp = arr[i];
        arr[i] = arr[(arr.length-1)-i];
        arr[(arr.length-1)-i] = temp;
     }
     System.out.println(Arrays.toString(arr));
Soumya Sarkar
  • 95
  • 1
  • 6
-6
int[] arrTwo = {5, 8, 18, 6, 20, 50, 6};

    for (int i = arrTwo.length-1; i > 0; i--)
    {
        System.out.print(arrTwo[i] + " ");
    }