简体   繁体   English

如何按升序对通用二维数组进行排序?

[英]How to sort a generic 2D array in ascending order?

I need to write up a generic method that takes as an input a generic 2D array and sorts it.我需要编写一个通用方法,该方法将通用二维数组作为输入并对其进行排序。 The method should use comparable or comparator.该方法应使用可比较或比较器。

The code I've written so far looks like this:到目前为止,我编写的代码如下所示:

public static <T extends Comparable<T>> void sort(T[][]stuff) {
    T swap = stuff[0][0];
    T temp;
    for (T[] row : stuff) {
        for (T elt : row) {
            if (elt.compareTo(swap) > 0) {
                temp= swap;
                swap = elt;
                elt = temp;
            }
        }
    }    
}

I took the idea from another StackOverflow post that showed how to get the biggest number from a 2D array and all this code does is this.我从另一个 StackOverflow 帖子中获得了这个想法,该帖子展示了如何从 2D 数组中获取最大数字,而这些代码所做的就是这个。

I will transform the array to a 1D array, then I will sorted and finally I will re-inserted the value in the 2D-array:我将数组转换为一维数组,然后进行排序,最后我将重新插入二维数组中的值:

public static <T extends Comparable<T>> void sort(T[][] stuff) {
    List<T> list = new ArrayList<T>();
    for (int i = 0; i < stuff.length; i++) {
        for (int j = 0; j < stuff[i].length; j++) {
            list.add(stuff[i][j]);
        }
    }
    Collections.sort(list);
    int len = stuff.length;
    for (int i = 0; i < len; i++) {
        for (int j = 0; j < len; j++) {
            stuff[i][j] = list.get(i * len + j);
        }
    }
}

You can first flatten this 2d array into a 1d array, then sort the flat array, and then replace the elements of the 2d array with elements from the sorted flat array.您可以先将这个二维数组展平为一维数组,然后对平面数组进行排序,然后将二维数组的元素替换为排序后的平面数组中的元素。

Try it online! 在线尝试!

public static <T extends Comparable<T>> void sort(T[][] array) {
    // flatten a 2d array into a 1d array and sort it
    Object[] sorted = Arrays.stream(array)
            .flatMap(Arrays::stream)
            .sorted(Comparator.naturalOrder())
            .toArray();

    // replace the elements of the 2d array
    // with elements from the sorted flat array
    AtomicInteger k = new AtomicInteger(0);
    IntStream.range(0, array.length)
            .forEach(i -> IntStream.range(0, array[i].length)
                    .forEach(j -> array[i][j] = (T) sorted[k.getAndIncrement()]));
}
public static void main(String[] args) {
    String[][] arr1 = {{"a", "b", "e"}, {"f", "d", "g"}, {"h", "c", "i"}};
    Integer[][] arr2 = {{3, 1, 4}, {5, 2}, {7}, {8, 6, 9}};

    sort(arr1);
    sort(arr2);

    // output
    System.out.println(Arrays.deepToString(arr1));
    // [[a, b, c], [d, e, f], [g, h, i]]
    System.out.println(Arrays.deepToString(arr2));
    // [[1, 2, 3], [4, 5], [6], [7, 8, 9]]
}

See also: Sorting through entire 2d array in ascending order另请参阅:按升序对整个二维数组进行排序

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM