嗨,大家好我在网站上搜索过java中的2D数组排序,它们只涉及一列。我想知道如何在每列中按字母顺序对2D数组进行排序。我尝试过使用比较器,但它只排序一列。
我必须按字母或反向字母顺序输出我的单词bank(取决于用户的选择)并输出一个表格。
String word[][] ={
{"The", "ball", "the", "book"},
{"It", "dog", "a/an", "efficiently"},
{"A/An", "has", "some", "dog"},
{"Laura", "ant", "rolled", "cat"},
{"William", "cat", "ran", "apple"},
{"Alex", "ate", "big", "pear"},
{"Chris", "smelled", "small", "slowly"},
{"Daniel", "planted", "jumped", "truck"},
{"Joshua", "washed", "rotten", "awkward"},
{"Rachel", "bear", "juicy", "shirt"},
{"Jimmy", "boiled", "roared", "plant"},
{"Emily", "liked", "vibrant", "away"},
{"Erin", "touched", "swam", "chair"},
{"Michael", "hippo", "long", "bicep"},
{"Steven", "grabbed", "short", "phone"},
{"Andrew", "kept", "massive", "quickly"},
};
所以示例输出将是:
A / An“\ t”ant“\ t”a / an“\ t”apple
安德鲁“\ t”吃了“\ t”多汁的“\ t”远离
亚历克斯“\ t”球“\ t”跳了“\ t”书
提前致谢!
答案 0 :(得分:1)
您需要按列重新排序数据,并对列进行排序。例如:
String word[][] ={
{"The", "ball", "the", "book"},
{"It", "dog", "a/an", "efficiently"},
{"A/An", "has", "some", "dog"},
{"Laura", "ant", "rolled", "cat"},
{"William", "cat", "ran", "apple"},
{"Alex", "ate", "big", "pear"},
{"Chris", "smelled", "small", "slowly"},
{"Daniel", "planted", "jumped", "truck"},
{"Joshua", "washed", "rotten", "awkward"},
{"Rachel", "bear", "juicy", "shirt"},
{"Jimmy", "boiled", "roared", "plant"},
{"Emily", "liked", "vibrant", "away"},
{"Erin", "touched", "swam", "chair"},
{"Michael", "hippo", "long", "bicep"},
{"Steven", "grabbed", "short", "phone"},
{"Andrew", "kept", "massive", "quickly"},
};
// generate the list of columns
List<List<String>> cols=new ArrayList<>();
for (String[] row:word){
for (int a=0;a<row.length;a++){
// create columns when needed
while(cols.size()<a+1){
cols.add(new ArrayList<String>());
}
List<String> col=cols.get(a);
col.add(row[a]);
}
}
// rewrite sorted words in word array
int colIdx=0;
for (List<String> col:cols){
// sort column
Collections.sort(col);
for (int a=0;a<col.size();a++){
word[a][colIdx]=col.get(a);
}
colIdx++;
}
// print
for (String[] row:word){
String sep="";
for (String w:row){
System.out.print(sep);
sep="\t";
System.out.print(w);
}
System.out.println();
}