Java Reference
In-Depth Information
One approach would be to create a new array and to store the values from the first
array into the second array in reverse order. Although that approach would be reason-
able, you should be able to solve the problem without constructing a second array.
Another approach is to conduct a series of exchanges or swaps. For example, the value
3 at the front of the list and the value 78 at the end of the list need to be swapped:
[0]
[1]
[2]
[3]
[4]
[5]
list
3
8
7
-2
14
78
swap these
After swapping that pair, you can swap the next pair in (the values at indexes
1 and 4):
[0]
[1]
[2]
[3]
[4]
[5]
list
78
8
7
-2
14
3
then swap
these
You can continue swapping until the entire list has been reversed. Before we look
at the code that will perform this reversal, let's consider the general problem of swap-
ping two values.
Suppose you have two integer variables x and y that have the values 3 and 78 :
int x = 3;
int y = 78;
How would you swap these values? A naive approach is to simply assign the val-
ues to one another:
// will not swap properly
x = y;
y = x;
Unfortunately, this doesn't work. You start out with the following:
xx3 y78
When the first assignment statement is executed, you copy the value of y into x :
x3
x78 y78
 
Search WWH ::




Custom Search