簡體   English   中英

Java將二維數組的行按升序排序,將列按降序排序

[英]Java Sorting a 2d array rows into ascending and columns into descending order

拜托,有人可以幫我嗎,我需要按降序對2d數組列進行排序? 我使用此代碼將數組行按升序排序,但現在必須將列按降序排序。

// Initialize array
static int[][] sortArray = new int[7][7];

public static void main(String args[]) {
    //initialize array values with random numbers
    for (int i = 0; i < sortArray.length; i++) {
        for (int j = 0; j < sortArray[i].length; j++) {
            sortArray[i][j] = (int) (Math.random() * 100);

        }
    }

    System.out.println("\n" + "Before sorting");
    displayArray();

    //Print out sorted array
    for (int i = 0; i < sortArray.length; i++) {
        bubbleSort(sortArray[i]);
    }

    System.out.println("\n" + "Array rows in ascending order");
    displayArray();

    //Print out sorted columns of array
    for (int i = 0; i < sortArray.length; i++) {
        sortSort(sortArray[i]);
    }

    System.out.println("\n" + "Array column in descending order");
    displayArray();

}

// Sort rows into ascending order
public static void bubbleSort(int[] numArray) {
    int n = numArray.length;
    int temp = 0;

    for (int i = 0; i < n; i++) {
        for (int j = 1; j < (n - i); j++) {
            if (numArray[j - 1] > numArray[j]) {
                temp = numArray[j - 1];
                numArray[j - 1] = numArray[j];
                numArray[j] = temp;
            }
        }
    }
}

//Sort cols into descending order
public static void sortSort(int[] colArray) {
    int n = colArray.length;
    int temp = 0;

    for (int i = 0; i < n; i++) {
        for (int j = 1; j < (n - i); j++) {
            if (colArray[j - 1] < colArray[j]) {
                temp = colArray[j - 1];
                colArray[j - 1] = colArray[j];
                colArray[j] = temp;
            }
        }
    }
}

//  Print out arrays
private static void displayArray() {
    int i, j = 0;

    System.out.println("-------------------------------------");
    System.out.println(" ");

    for (i = 0; i < sortArray.length; i++) {
        for (j = 0; j < sortArray[i].length; j++) {
            System.out.print(sortArray[i][j] + "\t" + "\t");
        }
        System.out.println();
    }
}
int[] colArray = new int[] { 2, 9, 4, 5};
int n = colArray.length;
int temp = 0;


for (int i = 0; i < n; i++) {
  for (int j = 1; j < (n - i); j++) {

      if (colArray[j - 1] > colArray[j]) {
          temp = colArray[j - 1];
          colArray[j - 1] = colArray[j];
          colArray[j] = temp;
      }

  }
 }
 Arrays.stream(colArray).forEach(data -> System.out.println(data));

只需更換

if (colArray[j - 1] < colArray[j]) {
...
}

有:

if (colArray[j - 1] > colArray[j]) {
...
}

>而不是<

首先,您的數組不是2D :),只是因為數組的每個元素都有一個像Arr [0]這樣被調用的數字,並且它的值例如是5,但這並不意味着它是2D的。

但是為了將數組降序排列,可以使用以下代碼:

            int n = intArray.length;
            int temp = 0;

            for(int i=0; i < n; i++){
                    for(int j=1; j < (n-i); j++){

                            if(intArray[j-1] < intArray[j]){
                                    //swap the elements!
                                    temp = intArray[j-1];
                                    intArray[j-1] = intArray[j];
                                    intArray[j] = temp;
                            }

                    }
            }

我重寫了您的sortSort方法以對列進行排序。 盡管這不應該是解決方案,但可以為您指明正確的方向。

這就是我想象的二維數組:

 _ _ _ _ _
|_|_|_|_|_|
|_|_|_|_|_|
|_|_|_|_|_| <rows
 ^
 cols

在代碼中,我會這樣看: myArray[row][col]

但更確切地說,它是一個數組數組,因此實際上看起來更像這樣:

 ______________ ______________ ______________
|  _ _ _ _ _   |  _ _ _ _ _   |  _ _ _ _ _   |
| |_|_|_|_|_|  | |_|_|_|_|_|  | |_|_|_|_|_|  |
|______________|______________|______________|
      ^              ^              ^
     row 0          row 1          row 2     

每行包含一個列數組。 這就是問題所在-您無法將第0行的數組與第1行的數組進行比較,並說哪個數組“更大” ...除非按大小將其排序。

在您的程序中,您這樣調用了列排序方法:

//Print out sorted columns of array
for (int i = 0; i < sortArray.length; i++) {
    sortSort(sortArray[i]);
}

該指數i遍歷行並調用sortSort 因此,對於i=0它采用第一行並將包含的列數組傳遞給sortSort 因此,您的方法只能對單個行的列進行排序。

sortSort(sortArray[i]);  // sortArray[i] represents all columns of row i

為了使其對列進行排序,它必須了解整個2D數組。 列和行。 這意味着您只能一次對整個數組排序,而不能對單個列排序。

讓我們在我的示例中看一下:

public static void sortSort(int[][] colArray) {  // we pass the whole 2D-array int[rows][cols]
    int n = colArray.length;    
    int temp = 0;

    // since every row contains a whole array, you cannot really sort the row itself.
    // But you can sort it by its columns value (confusing, I know - sorry)
    // we take the first row as reference (colArray[0])
    // and iterate over every column (from 0 to colArray[0].length)
    // that's a problem, but we get to that later
    for (int col = 0; col < colArray[0].length; col ++) {
        // your sorting loops are working, so we don't change them
        for (int i = 0; i < n; i++) {
            for (int j = 1; j < (n - i); j++) {
                // and here is the magic we compare row j with row j-1 of the current column (col)
                if (colArray[j - 1][col] < colArray[j][col]) {
                    temp = colArray[j - 1][col];
                    colArray[j - 1][col] = colArray[j][col];
                    colArray[j][col] = temp;
                }
            }
        }
    }
}

您可以測試此代碼,然后查看它是否有效。 但是,它只能在某些情況下工作!

我前面提到的問題是每一行都需要與第一行完全相同的列數:

This wouldn't work:
 _ _ _ _ 
|_|_|_|_|       <-- row 1 has 4 columns
|_|_|_|_ _ _    <-- row 2 only 3
|_|_|_|_|_|_|   <-- row 3 has 6 columns

如果您不必針對可變的列數進行此操作,請保留它。 如果您總是有一個漂亮的n行表,每行m列,那么上述方法就可以解決問題。

暫無
暫無

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

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