Sort 2d array by last row using Arrays.sort array

Is it possible to sort a 2d array by last row using Arrays.sort (,) in Java. The following snippet is great for sorting by the last column, but it seems that it cannot be configured to sort by the last row.

My first thought was to use converting columns to rows, doing sorting, and then converting rows to column. Any better way for very large arrays?

int[][] twoDim = { {1, 2, 3}, {3, 7, 11}, {8, 9, 16}, {4, 2,8}, {5, 3, 9} };
Arrays.sort(twoDim, new Comparator<int[]>() {
     @Override
     public int compare(int[] o1, int[] o2) {
         return ((Integer) o1[2]).compareTo(o2[2]);
     }
});

Think over the whole situation: This is where I, when my array is initialized, and you can represent this data set in rows and columns as follows:

{1, 2, 3}, //first row with three columns
{3, 7, 11}, //second row with three columns
{8, 9, 16},
{4, 2, 8},
{5, 3, 9} //last row with three columns

, 5 3. , : 2, 1, 3
7, 3, 11
9, 8, 16
2, 4, 8
3, 5, 9 //now it ordered by last row (first and second column have changed they position, by chance third column is in a right place already)

+3
3

, , .

:

1, 2, 3
3, 7, 11
8, 9, 16
4, 2, 8
5, 3, 9

, , :

{2, 7, 9, 2, 3}, {1,3,8,4,5}, {3, 11, 16, 8, 9}

, , , 4, 2, 8 5,3,9. , , , .

, .

+1

.

, . partition:

  • .
  • .

:

public void qsortOnLastRow(int[][] matrix, int left, int right) {
    if (left < right) {
        int i = partition(matrix, left, right);
        qsortOnLastRow(matrix, left, i - 1);
        qsortOnLastRow(matrix, i + 1, right);
    }
}

public int partition(int[][] matrix, int left, int right) {
    int lastrow = matrix.length - 1;
    int pivotValue = matrix[lastrow][left];
    int i = left;
    for (int j = left + 1; j <= right; j++) {
        if (matrix[lastrow][j] <= pivotValue) {
            i++;
            swapColumns(matrix, i, j);
        }
    }
    swapColumns(matrix, left, i);
    return i;
}

public void swapColumns(int[][] matrix, int c0, int c1) {
    if (c0 != c1) {
        for (int i = 0; i < matrix.length; i++) {
            int t = matrix[i][c0];
            matrix[i][c0] = matrix[i][c1];
            matrix[i][c1] = t;
        }
    }
}

int[][] matrix, qsortOnLastRow(matrix, 0, matrix[0].length - 1);

, , O(m * n * log n), m = n = .

. ( ) .

0

, . , . , Arrays.sort . , , , .

, :

  • , , , , .

  • . , , .

0

All Articles