# java - working - reverse the order of an array python

## Reverse Array Order (6)

I am trying to reverse the order of an Array in java.

What is the most efficient way to do so in O(n) with the least amount of memory used.

No need to answer with code, pseudo code will be fine.

Here is my thought process:

```
create a new temp array //I think this is a waste of memory,
//but I am not sure if there's a better way
grab elements from the end of the original array -decrement this variable
insert element in beginning of temp array -increment this variable
then make the original array point to the temp array? //I am not sure
//if I can do this in java; so let's say the
//original array is Object[] arr; and the temp array is
//Object[] temp. Can I do temp = arr; ?
```

Is there a better more efficient way to do this perhaps without using a temp array? and Lastly, assume that there are no nulls in the array, so everything can work. Thank you

Edit: no this is not homework.

Here's two solutions:

```
loop to N/2
swap each element at i with element at N - i
```

Another solution is (depending on your circumstances) fake reversing the array by indexing:

```
GetValueAt(int i){return array[N - i];}
```

If it's an Object array, then `Collections.reverse(Arrays.asList(array))`

will do the job with constant memory and linear time -- no temporary array required.

Use a single temp element.

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

You can Do this in just two steps

```
ArrayList<Element> YourTempElement= new ArrayList<Element>(mElements);
Collections.reverse(YourTempElement);
```

pseudocode, assuming 0-based-index arrays:

```
for i in range(0, len(array)/2):
swap(array[i], array[(len(array)-1)-i])
```

you can do it without needing a temp array

- loop from the beginning (or end doesn't matter) to the middle of the array
- swap element with element at (last element - index) (so 0 and
`size - 1`

, 1 and`size - 2`

etc) - you'll do something like this to swap:

temp = a[i]; a[i] = a[end-i]; a[end-i] = temp;

- repeat