Reverse Array Order

Solution 1:

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.

Solution 2:

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

Solution 3:

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.)

Solution 4:

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