如何按列对2D整数数组排序 [英] How to sort a 2D integer array by columns
本文介绍了如何按列对2D整数数组排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我们有一个二维int数组,如下所示:
If we have a 2D int array that looks like this:
6 | 8 | 9 | 16
0 | 6 |-3 | 4
18| 2 | 1 | 11
超出预期的输出将是:
0 | 2 |-3 | 4
6 | 6 | 1 | 11
18| 8 | 9 | 16
当我想到如何垂直排序时,我会阻止.
I block when when i think of it how to sort vertically.
int[][] array = new int[10][10];
for(int i = 0; i < array.length; i++){
for(int j = 0; j < array[0]; j++){
//here i block because i don't know how i would vertically sort them
}
}
我知道有很多与此相关的主题,而在所有主题中,没有一个主题对我有用.因此,我为这篇文章表示歉意,但我被困住了.
I know there are a lot of topics about this and in all of them not one of them worked for me. Therefore I apologize for this post but I am stuck.
推荐答案
了解线性代数请:
带有矩阵转置
public class MatrixSort {
private static final int MATRIX[][] = {
{ 6, 8, 9, 16 },
{ 0, 6, -3, 4 },
{ 18, 2, 1, 11 }
};
private static int[][] transpose(int[][] m) {
int[][] ret = new int[m[0].length][m.length];
for (int i = 0; i < m.length; i++)
for (int j = 0; j < m[0].length; j++)
ret[j][i] = m[i][j];
return ret;
}
public static void main(String[] args) {
int ret[][] = transpose(MATRIX);
for(int i=0; i < ret.length; i++) {
Arrays.sort(ret[i]);
}
ret = transpose(ret);
for(int i=0; i < ret.length; i++) {
for(int j=0; j < ret[i].length; j++) {
System.out.print(ret[i][j]);
System.out.print(" | ");
}
System.out.print('\n');
}
}
}
这篇关于如何按列对2D整数数组排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文