Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reversing an array of characters without creating a new array

How can I reverse an array in place (without creating a new array)?

like image 319
miriam Avatar asked Nov 27 '22 19:11

miriam


2 Answers

public static int[] reverseArrayWithoutTempArray(int[] array) {
    int i = 0, j = array.length - 1;
    for (i = 0; i < array.length / 2; i++, j--) {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
    return array;
}
like image 137
Asad Rao Avatar answered Dec 10 '22 09:12

Asad Rao


Homework means pseudo-code only from me, which you've made relatively easy by not specifying what language you want anyway :-)

Turn this into your language of choice:

Set i1 to index of first element in array
Set i2 to index of last element in array
while i1 < i2:
    Set temporary variable to element number i1
    Set element number i1 to element number i2
    Set element number i2 to temporary value
    Add 1 to i1
    Subtract 1 from i2

An ideal thing to do is to actually run that algorithm in your head, using a piece of paper to keep track of variables:

  • each the elements in the array.
  • i1 and i2.
  • temporary variable.

I tend to do that for simpler algorithms. Harder ones I insert debug statement into so that the computer can do that grunt work for me. Start with a piece of paper thus:

i1 | i2 | tempvar | el[0] | el[1] | el[2] | el[3] | el[4] | el[5]
---+----+---------+-------+-------+-------+-------+-------+------
                      H       e       l       l       o       !

and just run through the steps one by one, checking and/or changing each column as you go. That will result in you understanding how it works far better than just being given some code.

like image 41
paxdiablo Avatar answered Dec 10 '22 08:12

paxdiablo