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 co
Lets consider the array is of array of Integer then we could also look for a solution like this
arr - array of Integer
for(int i=0,int J<arr.length-1 ; i<j ; i++,j--)
{
temp =a[i];
a[i]=a[j];
a[j]=temp;
}
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.
You can Do this in just two steps
ArrayList<Element> YourTempElement= new ArrayList<Element>(mElements);
Collections.reverse(YourTempElement);
you can do it without needing a temp array
size - 1
, 1 and size - 2
etc)temp = a[i]; a[i] = a[end-i]; a[end-i] = temp;
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 don't need to use a temporary array; just step through the array from the beginning to half-way through, swapping the element at i
for the element at array.length-i-1
. Be sure the handle the middle element correctly (not hard to do, but do make sure.)