数组行排序
注意一个细节,就是在每一行排序时要注意列标是i——j-1(不包含j),还有就是二维数组的每一行列走位都一样
import java.util.*;
class rowTest{
public static void main(String[] args){
Double[][] a = new Double[3][3];
System.out.println("Enter a 3-by-3 matrix row by row:");
Scanner input = new Scanner(System.in);
String str="";
for(int i=0;i<a.length;i++)
for(int j=0;j<a[0].length;j++)
a[i][j] = input.nextDouble();
System.out.println("paixu:");
Arrays.sort(a[0],0,3);
Arrays.sort(a[1],0,3);
Arrays.sort(a[2],0,3);
for(int i=0;i<a.length;i++){
for(int j=0;j<a[0].length;j++){
System.out.print(a[i][j]+" ");
}
System.out.println();
}
}
}
列排序
初思路:
import java.util.*;
class test{
public static double[][] sortColumns(double [][] m){
double [][] b=new double [3][3];
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
b[i][j]=m[j][i];
}
}
Arrays.sort(b[0],0,3);
Arrays.sort(b[1],0,3);
Arrays.sort(b[2],0,3);
double [][]c=new double[3][3];
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
m[i][j]=b[j][i];
}
}
return m;
}
public static void main(String[] args){
double[][] a = new double[3][3];
System.out.println("Enter a 3-by-3 matrix row by row:");
Scanner input = new Scanner(System.in);
for(int i=0;i<a.length;i++)
for(int j=0;j<a[0].length;j++)
a[i][j] = input.nextDouble();
System.out.println("paixu:");
sortColumns(a);
for(int i=0;i<a.length;i++){
for(int j=0;j<a[0].length;j++){
System.out.print(a[i][j]+" ");
}
System.out.println();
}
}
}
与上述一样:
import java.util.*;
class columntest {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
double[][] testMatrix = new double[3][3];
for(int i=0;i<testMatrix.length;i++)
for(int j=0;j<testMatrix[0].length;j++)
testMatrix[i][j] = input.nextDouble();
System.out.println("---------before---------");
for(int i=0;i<testMatrix.length;i++) {
for(int j=0;j<testMatrix[0].length;j++) {
System.out.print(testMatrix[i][j]+" ");
}
System.out.println();
}
double[][] target = transpose(testMatrix);
Arrays.sort(target[0],0,3);
Arrays.sort(target[1],0,3);
Arrays.sort(target[2],0,3);
double[][] array = transpose(target);
System.out.println("---------after---------");
for(int i=0;i<array.length;i++) {
for(int j=0;j<array[0].length;j++) {
System.out.print(array[i][j]+" ");
}
System.out.println();
}
}
public static double[][] transpose(double[][] matrix){
double[][] result = new double[matrix[0].length][matrix.length];
for(int i=0; i<matrix.length; i++) {
for(int j=0; j<matrix[i].length; j++) {
result[j][i] = matrix[i][j];
}
}
return result;
}
}
(PS:列排序稍微麻烦一点点…)