[英]Sort each row in 2D array without changing the original
我正在尝试对数组m1进行排序并打印它
import java.util.Arrays;
public class Foo {
public static void main(String[] args) {
int[][] m1 = { { 14, 11, 13, 12 },
{ 18, 15, 13, 13 },
{ 19, 16, 15, 17 } };
int[][] temp = m1.clone();
sortRows(m1);
displayArray(m1);
m1 = temp;
}
public static int[][] sortRows(int[][] m) {
for (int i = 0; i <= 2; i++) {
Arrays.sort( m[i] );
}
return m;
}
public static void displayArray(int[][] m) {
//method to print array
}
}
如何删除数组重复并恢复到main方法中的原始数据? 我想将它移动到SortArrays方法
多维数组中的每个数组(在Java中)也是一个Object
,因此您需要对每个数组执行深层复制。 如果我理解你的问题,你可以做类似的事情
public static void main(String[] args) {
int[][] m1 = { { 14, 11, 13, 12 }, { 18, 15, 13, 13 },
{ 19, 16, 15, 17 } };
int[][] temp = new int[m1.length][]; // <-- a new array for the copies.
for (int i = 0; i < m1.length; i++) {
temp[i] = m1[i].clone(); // <-- copy each row.
Arrays.sort(temp[i]); // <-- sort each row.
}
System.out.println("Original: " + Arrays.deepToString(m1));
System.out.println("Sorted copy: " + Arrays.deepToString(temp));
}
输出是
Original: [[14, 11, 13, 12], [18, 15, 13, 13], [19, 16, 15, 17]]
Sorted copy: [[11, 12, 13, 14], [13, 13, 15, 18], [15, 16, 17, 19]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.