How can I reverse an array in place (without creating a new array)?
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;
}
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:
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.
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