0

So I have a 2d array of states and capitals like this:

String[][] statesAndCapitals = {
                    { "Alabama", "Montgomery" },
                    { "Alaska", "Juneau" },
                    {"Arizona", "Phoenix"} ,
                    {"Arkansas", "Little Rock"},
                    {"California", "Sacramento"}...

and I need to bubble sort this array alphabetically by the capital or [1] index of each row. (without Arrays.sort)

This is what i have so far...

public static void bubbleSort(String[][] array) {
    for(int i = 0; i < array.length - 1; i++){
        for(int j = 0; j < array.length; j++) {
            if(array[i][1].compareTo(array[i + 1][1]) < 0)  {
                String[] temp = array[i];
                array[i] = array[i + 1];
                array[i + 1] = temp;
            }
        }
    }
}
Joe Guida
  • 29
  • 5
  • Possible duplicate of [Sort a two dimensional array based on one column](https://stackoverflow.com/questions/4907683/sort-a-two-dimensional-array-based-on-one-column) – DevilsHnd - 退職した May 25 '19 at 03:48

1 Answers1

1

Bubble sort requires two nested for-loops, such as is shown here: https://codereview.stackexchange.com/questions/58178/bubble-sorting-an-int-array

Also, I think your < should maybe be > on the third line of your code, but I guess it depends if you want alphabetical or reverse alphabetical.

mapeters
  • 1,067
  • 7
  • 11