繁体   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