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!