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.
Reverse(Array)Reverses the sequence of the elements in the entire one-dimensional Array.
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.
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.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With