For an assignment I had to do a Bubble Sort on a 2D array of states and their state capitals. The name of the array is stateCapitals. I am supposed to sort by the state capitals.
This is the 2D array:
String[][] stateCapitals = {
{"Alabama", "Montgomery"},
{"Alaska", "Juneau"},
{"Arizona", "Phoenix"},
{"Arkansas", "Little Rock"},
{"California", "Sacramento"},
{"Colorado", "Denver"},
...
};
(continues for all 50 states.)
This is what I have for the Bubble Sort:
for (int i = 0; i < stateCapitals.length - 1; i++) {
for (int j = 0; j < stateCapitals.length - i - 1; j++) {
if (stateCapitals[j][1].compareToIgnoreCase(stateCapitals[j + 1][1]) > 0) {
String[] temp = stateCapitals[j];
stateCapitals[j] = stateCapitals[j + 1];
stateCapitals[j + 1] = temp;
}
}
}
I have never done Bubble Sort on a 2D array before and am having trouble understanding it. How does this work? I understand how Bubble Sort works, but am having trouble understanding how the implementation works. What I mean is, how does this statement perform the sort step by step?
I've been looking at it and researching for a while and need a fresh perspective.
I would really appreciate some help.
Thanks!
The basic idea of bubble sort is to find the largest item, and move it step-by-step (bubble it) to the last position on the first iteration. The second iteration will bubble the 2nd largest item to the next to last position. The third iteration ...
You said you understand how bubble sort works, so this answer will be about 2D arrays.
Java doesn't have true 2D arrays. But, in Java, an array is an
Object. And Java allows arrays of Objects.A consequence is arrays of arrays are allowed. It's like nested arrays. Arrays can be "nested" to provide the functionality of 2D, 3D, 4D, etc. arrays.
Suppose code has
Foo [][] arr = new Foo [5][7];. It may help to think ofarras having 5 rows, where each row has 7 columns. A row may be accessed as a single unit:Foo [] bar = arr [3];Of course, a variable may be used to specify the row:bar = arr [rowIndex];Note that that code does not result in copying. The variable
baris an alias for one of the rows ofarr.The variable
stateCapitalsin your code is an array of array ofString. One row has twoStringObjects: A state name, and the name of the capital for that state.This works the same as swapping any other pair of Objects: