【发布时间】:2018-01-03 19:36:02
【问题描述】:
任务是对矩阵的每一列进行升序和降序排序 可互换顺序,例如第一列被排序 升序,降序第二,升序第三等等......
只能使用普通数组和矩阵,所以不能使用 Hashmaps、Sets、Lists 或类似的东西。
到目前为止,我有这个,这只是一个想法,但我必须承认我已经卡在这里了。
public class TwoDimArray {
static void enterMatrix(int[][] a, int m, int n) {
Scanner scan = new Scanner(System.in);
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.println("Enter " + i + " column matrice...\nEnter" + j + " row matrice...");
a[i][j] = scan.nextInt();
}
}
System.out.println("Final matrix\n");
printMatrix(a, m, n);
}
static void printMatrix(int[][] a, int m, int n) {
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(a[i][j]);
}
System.out.println();
}
}
static void sortMatriceColumn(int[] a, int n) {
// My idea was to create static method like this and call it for each column
//while iterating through matrix, so as the method for descending sort, but
//I am not quite sure of how to
//implement
// this to the end
int temp;
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++) {
if (a[i] > a[j]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
System.out.print("Ascending Order:");
for (int i = 0; i < n - 1; i++) {
System.out.print(a[i] + ",");
}
System.out.print(a[n - 1]);
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of matrix rows and cols...");
int rowNum= scan.nextInt();
int colNum= scan.nextInt();
int[][] a = new int[rowNum][colNum];
enterMatrix(a, rowNum, colNum);
}
}
编辑:
另外,我在这里越界了。
static void sortMatriceColumn(int[][] a, int rowNum, int colNum)
{
//int temp;
int i,j = 0,k;
for ( i = 0; i < rowNum; i++) {
for ( j = 0; j < colNum; j++) {
for ( k = j + 1 ; k < colNum; k++) {
if (a[i][j] > a[i][k]) {
int temp1= a[i][j];
a[i][j]=a[i][k];
a[i][k]=temp1;
}
}
}
}
for(int l11 = 0; l11 < rowNum-1 ; l11++) {
System.out.print(" " + a[l11][j]);
}
}
【问题讨论】:
-
这看起来像是一个家庭作业,你已经完成了大约 80%。您的列排序功能几乎是冒泡排序,但您错过了查看数组是否已排序的测试。接下来,要么实现升序和降序版本,要么使您的分拣机能够根据输入参数前进或后退。您可以谷歌冒泡排序 java,或者只是排序 java 以查看示例代码和排序选项。
标签: java arrays sorting matrix