Java Reference
In-Depth Information
Now we just need to write the code to find all the inversions for a given first value.
That requires us to write a second, nested loop:
for (every possible first value) {
for (every possible second value) {
if (first value > second value) {
print(first, second).
}
}
}
This problem is fairly easy to turn into Java code, although the loop bounds turn
out to be a bit tricky. For now, let's use our standard traversal loop for each:
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data.length; j++) {
if (data[i] > data[j]) {
System.out.println("(" + data[i] + ", " + data[j] + ")");
}
}
}
The preceding code isn't quite right. Remember that for an inversion, the second
value has to appear after the first value in the list. In this case, we are computing all
possible combinations of a first and second value. To consider only values that come
after the given first value, we have to start the second loop at i + 1 instead of start-
ing at 0 . We can also make a slight improvement by recognizing that because an
inversion requires a pair of values, there is no reason to include the last number of
the list as a possible first value. So the outer loop involving i can end one iteration
earlier:
for (int i = 0; i < data.length - 1; i++) {
for (int j = i + 1; j < data.length; j++) {
if (data[i] > data[j]) {
System.out.println("(" + data[i] + ", " + data[j] + ")");
}
}
}
When you write nested loops like these, it is a common convention to use i for
the outer loop, j for the loop inside the outer loop, and k if there is a loop inside the
j loop.
 
Search WWH ::




Custom Search