我需要编写一个通用方法,该方法将通用二维数组作为输入并对其进行排序。该方法应使用可比较或比较器。
到目前为止我写的代码是这样的:
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;
}
}
}
}
我从另一篇 StackOverflow 帖子中获得了这个想法,该帖子展示了如何从 2D 数组中获取最大数字,而这些代码所做的就是这样。
答案 0 :(得分:0)
我将数组转换为一维数组,然后我将排序,最后我将重新插入二维数组中的值:
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);
}
}
}
答案 1 :(得分:0)
可以先将这个二维数组展平成一维数组,然后对平面数组进行排序,然后用排序后的平面数组中的元素替换二维数组的元素。
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]]
}