Sorting 2D String Array with BUBBLESORT in java

时光总嘲笑我的痴心妄想 提交于 2019-12-23 19:29:50

问题


Similar questions have been asked but never about 2D String Arrays, therefore after trying for a long time I couldn't find what I wanted. I'm trying to sort a 2D String Array in java using BubbleSort.

As input, I receive a two-dimensional array (a table) of Strings and the index of the “column” you should sort. I should sort the rows by the values in the indicated column.

You can see the first index as a row index, and the second index as a column index. For example, the following Java array and table correspond with each other:

String[][] table = {
  {"a", "b"},
  {"c", "d"}
};

-

0   1
  +---+---+
0 | a | b |
  +---+---+
1 | c | d |
  +---+---+

To continue on this example, table[0][1] will yield the value "b", since it’s the item in row 0 and column 1.

IMPORTANT: I am not allowed to use any sorting algorithm from the Java library, for example Arrays.sort.

This is what I've tried so far:

class Solution {
        public static void stableSort(String[][] table, int column) {
            int i;
            int j;
            String temp = null;
            for (i = 0; i < table.length - 1; i++) {
                for (j = 0; j < table.length - 1 - i; j++) {
                    if (table[i][j].compareTo(table[i][j + 1]) > 0) {
                        temp = table[i][j];
                        table[i][j] = table[i][j + 1];
                        table[i][j + 1] = temp;
                    }
                }
            }
        }
    }

I get an Index out of Bounds error and also it is not working as the test expects a different result in table[0][0] Thanks for your help.


回答1:


My working solution:

import java.util.Arrays;

public class MySolution {
    public static void stableSort(String[][] table, int column) {
        String[] temp = null;
        int rows = table.length;
        for (int i = 0; i < rows; i++) {
            for (int j = 1; j < (rows - i); j++) {
                if (table[j - 1][column].compareTo(table[j][column]) > 0) {
                    temp = table[j - 1];
                    table[j - 1] = table[j];
                    table[j] = temp;
                }
            }
        }
    }

    public static void main(String[] args) {
        String[][] table = { { "c", "d" }, { "a", "b" } };
        printTable(table);
        stableSort(table, 1);
        printTable(table);
    }

    private static void printTable(String[][] table) {
        System.out.println("table:");
        for (int i = 0; i < table.length; i++) {
            System.out.println(Arrays.toString(table[i]));
        }
    }
}

some notes for you:

  1. use meaningful names (rows is easier to understand than table.length)
  2. bubble sort loops were a bit off, there are plenty of examples of how to do it online
  3. as mentioned, you should start by doing it for 1d array and then "generalize" it
  4. one big issue you had: using j (which should be the index of the row to compare to) as the column (and ignoring column)
  5. another big issue is only substituting the element (instead of the rows)

I hope this helps you!

EDIT: I just noticed you've also switched between row and column in your code (in your explanation the first index denotes the row, in your code it seems like the opposite is correct)




回答2:


public static String[][] stableSort(String[][] table, int column) {
    int i=0,j=0;
    String[] temp = null;
    boolean swap=true;
    while(swap)
    for (i = 0; i < table.length - 1; i++) {
        swap=false;
        if(table[i][column].compareTo(table[i+1][column]) > 0){
            temp = table[i];
            table[i] = table[i+1];
            table[i+1]=temp;
            swap=true;
        }
    }
    return table;
}

It keeps applying the bubblesort until no more swaps are performed. At that point,the condition while(swap) is no longer satisfied and the method returns. Tried in a main and it works (if I understand what you meant):

public static void main(String[] args) {
    String[][] table = {
            {"z", "b", "v"},
            {"s", "w", "a"},
            {"r", "c", "h"}
    };

    table = stableSort(table,1);
    for(int i = 0; i < table.length; i++){
        for(int j = 0; j < table[0].length; j++){
            System.out.printf("%5s ", table[i][j]);
        }
        System.out.println();
    }
}

this outputs:

z     b     v 
r     c     h 
s     w     a 



回答3:


EDIT: Working and no errors

If I take your exact sort but add a if statement for the switching of rows, add an exterior loop to run through the 2D array the length times the width and change the for loop control to '<=' then I get the following

   for(int z = 0; z < table.length * table.length; z++) // exterior for loop to run through the loop multiple times
   {
       for (i = 0; i <= table.length - 1; i++) {
           for (j = 0; j <= table.length - 1; j++) {
              if(j == table.length -1 && i == table.length-1) // If we are at the end then we can continue either to the next iteration or to the end of program
                  continue;
              if(j == table.length -1) // If you are ate the end of the row compare to the next row
              {
                   if (table[i][j].compareTo(table[i+1][0]) > 0) {
                       temp = table[i][j];
                       table[i][j] = table[i+1][0];
                       table[i+1][0] = temp;
                   } 
              }
              else if (table[i][j].compareTo(table[i][j + 1]) > 0) {
                   temp = table[i][j];
                   table[i][j] = table[i][j + 1];
                   table[i][j + 1] = temp;
              }
           }
       }
   }

I saw what you were trying to do by minimizing the number of checks when you put

table.length - 1 - i

That is good for efficiency but first attempt to get the sorting working. then trim it down to preform better.

Also I don't have a compiler in-front of me so code could have some errors




回答4:


to start, make it a 1d array or at least 1d indexable much easier formula:

x = (int)index/(int)rows
y = index % rows

with that you can use 1 variable index and index a 2d array and this is a bubblesort

def sort(self):
    for passnum in range(len(self.array)-1,0,-1):
        for i in range(passnum):
            if self.array[i]>self.array[i+1]:
                temp = self.array[i]
                self.array[i] =  self.array[i+1]
                self.array[i+1] = temp


来源:https://stackoverflow.com/questions/54202971/sorting-2d-string-array-with-bubblesort-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!