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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With