我对排序有疑问。
int[][] array = {{4,2},{1,7},{4,5},{1,2},{1,1},{4,1}};
对此数组进行排序后,它将变为如下。
int[][] array = {{1,1},{1,2},{1,7},{4,1},{4,2},{4,5}};
我对此感到困惑,如果我首先对行执行排序并在第二行对列执行排序,那么当我对行和列进行排序时,如何在同一时间更改两个值。
答案 0 :(得分:0)
看这个例子......
Sort a two dimensional array based on one column
The first column is a date of format "yyyy.MM.dd HH:mm" and the second column is a String.
既然你说2-D数组,我假设“格式日期......”表示一个字符串。这是用于对String [] []:
的二维数组进行排序的代码import java.util.Arrays; import java.util.Comparator;
public class Asdf {
public static void main(final String[] args) {
final String[][] data = new String[][] {
new String[] { "2009.07.25 20:24", "Message A" },
new String[] { "2009.07.25 20:17", "Message G" },
new String[] { "2009.07.25 20:25", "Message B" },
new String[] { "2009.07.25 20:30", "Message D" },
new String[] { "2009.07.25 20:01", "Message F" },
new String[] { "2009.07.25 21:08", "Message E" },
new String[] { "2009.07.25 19:54", "Message R" } };
Arrays.sort(data, new Comparator<String[]>() {
@Override
public int compare(final String[] entry1, final String[] entry2) {
final String time1 = entry1[0];
final String time2 = entry2[0];
return time1.compareTo(time2);
}
});
for (final String[] s : data) {
System.out.println(s[0] + " " + s[1]);
}
}
}