简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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