【发布时间】:2015-11-29 17:43:19
【问题描述】:
在课堂上,我们的老师要求我们对数组列表进行排序,然后将其作为 2D 数组返回,并打印每个更改。
这是数组:35、7、63、42、24、21 最后程序应该像这样打印出来:
[7 35 63 42 24 21]
[7 21 63 42 24 35]
[7 21 24 42 63 35]
[7 21 24 35 63 42]
[7 21 24 35 42 63]
[7 21 24 35 42 63]
我有以下代码,但不知何故它根本不起作用(注意 public static void 已经给出,所以我们必须实现 public static int[][] selectionsort(int[] a)
这有什么问题?
public static void main(String[] args) {
int[] a = new int[] { 35, 7, 63, 42, 24, 21 };
int[][] c = selectionsort(a);
for (int i = 0; i < c.length; i++){
System.out.print("[ ");
for (int j = 0; j < c[i].length; j++) {
System.out.print(c[i][j]+" ");
}
System.out.println("]");
}
/*
* expected printout
* [ 7 35 63 42 24 21 ]
* [ 7 21 63 42 24 35 ]
* [ 7 21 24 42 63 35 ]
* [ 7 21 24 35 63 42 ]
* [ 7 21 24 35 42 63 ]
* [ 7 21 24 35 42 63 ]
*/
}
public static int[][] selectionsort(int[] a) {
for (int i = 0; i < a.length - 1; i++) {
for (int j = i + 1; j < a.length; j++) {
if (a[i] > a[j]) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
return a;
}
【问题讨论】:
-
您需要创建一个二维数组来填充并在选择排序中返回,而不是返回参数a。
-
好的,我明白了,但我该怎么做呢?我是新手,我真的不知道......
-
您的老师想要的是您在排序算法的每次迭代中创建一个正在排序的数组的副本,并将该副本存储为数组或 int 数组的元素。算法完成后,返回包含所有中间副本的数组数组。因此,谷歌搜索“如何在 Java 中定义二维数组”和“如何在 Java 中创建数组的副本”。
-
Java 中的选择排序:pastebin.com/VUd9WHWE
标签: java arrays sorting multidimensional-array selection-sort