簡體   English   中英

以升序對2D數組排序

[英]Sort 2D array in ascending order

        class arrayDemo {

            static void sort2D(int[][] B) {

             boolean swap = true;
             int oy=0;
             int temp=0;

             for(int ox=0;ox<B.length;ox++){
                 while(oy<B[ox].length) {
                     while(swap) {
                     swap = false;
                         for(int ix=0;ix<B.length;ix++) {
                             for(int iy=0;iy<B[ix].length;iy++) {
                                     if(B[ox][oy]<B[ix][iy]) {
                                     temp = B[ix][iy];
                                     B[ix][iy] = B[ox][oy];
                                     B[ox][oy] = temp;
                                     swap = true;
                                     }
                                 }
                             }           
                     }
                 oy++; 
                 }
             } 
             for(int row=0;row<B.length;row++)
             for(int col=0;col<B[row].length;col++)
             System.out.println(B[row][col]);
             }

public static void main(String...S) {

     int y[][] = {{10,20,0,30},{10,5,8},{3,9,8,7},{2,3}};
     sort2D(y);
}    
}

我正在嘗試按升序對2D數組進行排序。

輸入:{{10,20,0,30},{10,5,8},{3,9,8,7},{2,3}}; 輸出:30,20,10,10,9,8,8,7,5,3,0,2,3

有人可以幫我知道我的代碼有什么問題嗎?

您正在比較不在同一行或同一列中的元素。 每個子數組應單獨排序。 if (B[ox][oy] < B[ix][iy])可能需要重新考慮這一行。

該代碼有很多問題。

  1. 它拋出ArrayIndexOutOfBoundsException 這是因為所有for循環測試都針對B.length進行測試,這對於內部數組而言是不正確的。
  2. 您正在比較每對元素,但是有些對與其他對相反,因此不應測試反向對。 您需要通過從另一個索引開始來限制內部for循環集的范圍。

為了解決所有這些問題,阻力最小的方法是將2D數組轉儲到1D數組中並對其進行排序,這要容易得多。

這是經過測試並證明可以正常工作的代碼:

static void sort2D(int[][] B) {

        int count = 0;
        for (int[] is : B)
            for (int i : is)
                count++;
        int[] A = new int[count];
        count = 0;
        for (int[] is : B)
            for (int i : is)
                A[count++] = i;

        int temp;
        for (int i = 0; i < A.length; i++)
            for (int j = i + 1; j < A.length; j++)
                if (A[i] > A[j]) {
                    temp = A[i];
                    A[i] = A[j];
                    A[j] = temp;
                }
        for (int i = 0; i < A.length; i++)
                System.out.print(A[i] + ",");

}

暫無
暫無

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

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