Java Reference
In-Depth Information
other values the same. In other words, you want to move the 3 to the back, yielding
the list (8, 9, 7, 5, 3). Let's explore how to write code to perform that action.
Suppose you have a variable of type int[] called list of length 5 that stores the
values (3, 8, 9, 7, 5):
[0]
[1]
[2]
[3]
[4]
list
3
8
9
7
5
The shifting operation is similar to the swap operation discussed in the previous
section, and you'll find that it is useful to use a temporary variable here as well. The
3 at the front of the list is supposed to go to the back of the list, and the other values
are supposed to rotate forwards. You can make the task easier by storing the value at
the front of the list (3, in this example) into a local variable:
int first = list[0];
With that value safely tucked away, you now have to shift the other four values to
the left by one position:
[0]
[1]
[2]
[3]
[4]
list
3
8
9
7
5
list
8
9
7
5
5
The overall task breaks down into four different shifting operations, each of which
is a simple assignment statement:
list[0] = list[1];
list[1] = list[2];
list[2] = list[3];
list[3] = list[4];
Obviously you'd want to write this as a loop rather than writing a series of individ-
ual assignment statements. Each of the preceding statements is of the form
list[i] = list[i + 1];
You'll replace list element [i] with the value currently stored in list element [i + 1] ,
which shifts that value to the left. You can put this line of code inside a standard tra-
versing loop:
for (int i = 0; i < list.length; i++) {
list[i] = list[i + 1];
}
 
Search WWH ::




Custom Search