Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse Array Order

Tags:

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.

like image 364
marcwho Avatar asked Apr 03 '12 14:04

marcwho


People also ask

What does array reverse do?

Reverse(Array)Reverses the sequence of the elements in the entire one-dimensional Array.

How do you reverse the order of an array in Python?

Using flip() function In this method, we can easily use the Python function flip() to reverse an original array. The flip() method is used to reverse the order of values in an array along the given axis.

How do you reverse an array without changing the original array?

To reverse an array without modifying the original:Use the spread syntax (...) to create a copy of the array. Call the reverse() method on the copy. The final array will contain the elements in reversed order.


2 Answers

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.

like image 168
Louis Wasserman Avatar answered Sep 19 '22 18:09

Louis Wasserman


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;   } 
like image 45
ArjunShankar Avatar answered Sep 21 '22 18:09

ArjunShankar