簡體   English   中英

使用 Arrays.sort 按最后一行對二維數組進行排序

[英]Sorting 2d-array by last row with Arrays.sort

是否可以使用 Java 中的 Arrays.sort(,) 按最后一行對二維數組進行排序。 以下代碼段非常適合按最后一列排序,但似乎沒有辦法調整按最后一行排序。

我的第一個想法是使用將列轉換為行,進行排序,然后將行轉換為列。 對於非常大的 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]);
     }
});

讓我們詳細說明一下整個情況:這就是我的數組被初始化的地方,你可以通過行和列來想象這個數據集如下:

{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

按最后一行排序意味着重新排列第一列和第二列的 position,因為 5 大於 3。所以在重新排列數據集后它看起來像:
2, 1, 3
7, 3, 11
9, 8, 16
2, 4, 8
3, 5, 9 //now it's ordered by last row (first and second column have changed they position, by chance third column is in a right place already)

如果我正確理解列和行的含義,則無法回答此問題。

如果你看這樣的數據集:

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,94, 2, 8顯然不會出現這種情況。 因此,您必須要么提出標准排序,要么找到不同的方法來解決您面臨的實際問題。

如果您正在處理矩陣,我強烈推薦一個library

有趣的問題。

我會通過實現快速排序的變體來做到這一點。 變化基本上在partition function 中:

  • 您使用矩陣的最后一行作為要排序的數組
  • 交換兩個元素時,實際上交換矩陣的兩列

這是一個實現:

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;
        }
    }
}

您可以通過調用qsortOnLastRow(matrix, 0, matrix[0].length - 1)對您的int[][] matrix進行排序;

如果我沒記錯的話,復雜性應該是O(m * n * log n) ,其中 m = 行數, n = 矩陣中的列數。

注意:您也可以將相同的技巧(在最后一行排序並交換列)與其他排序算法一起使用。

請記住,二維 arrays 是 arrays 的 arrays。 每個排序算法都需要一個工具來移動要排序的條目。 您按最后一列排序的解決方案有效,因為Arrays.sort將您的內部 arrays 視為要排序的對象。 您所謂的按最后一行排序,沒有等效的 object,它應該代表列。

所以你有兩個選擇:

  1. 實現您自己的排序算法,一次交換整個列,但請使用教科書算法。

  2. 轉置你的矩陣。 但是請記住,如果可以在整個程序中交換第一個和第二個索引的含義,這可能是免費的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM