【发布时间】:2019-11-14 05:49:48
【问题描述】:
我正在尝试从最小到最大对数字列表进行排序并打印出来。我尝试了两件事:
1.
public class Sorter {
public static void main(String[] args) {
int[] numbers = {1, 3, 8, 2, 5, -2, 0, 7, 15};
int[] sorted = new int[numbers.length];
for (int a = 0; a < numbers.length; a++) {
int check = 0;
for (int b = 0; b < numbers.length; b++) {
if (numbers[a] < numbers[b]) {
check++;
}
}
sorted[check] = numbers[a];
}
for (int c = numbers.length - 1; c >= 0; c--) {
System.out.print(sorted[c] + ", ");
}
}
}
这个东西有效,但不能使用重复的值,所以我尝试了另一个东西
public class Sortertwo {
public static void main(String[] args) {
int[] numinput = {3, 2, 1, 4, 7, 3, 17, 5, 2, 2, -2, -4};
int[] numsorted = new int[numinput.length];
int n = 0;
for (; n < numinput.length; ) {
for (int b = 0; b < numinput.length; b++) {
int check = 0;
for (int c = 0; c < numinput.length; c++) {
if (numinput[b] <= numinput[c]) {
check++;
}
}
if (check >= (numinput.length - n) && numinput[b] != 0) {
numsorted[n] = numinput[b];
numinput[b] = 0;
n++;
}
if (n >= (numinput.length)) {
break;
}
}
}
for (int g = 0; g < numinput.length; g++) {
System.out.print(numsorted[g] + ", ");
}
}
}
它依赖于一旦使用第一个数组中的数字(找到最小的),当程序下次遍历数组时必须忽略它。
我尝试将它分配为null 值,但它不起作用,所以我将它分配为零然后忽略它,这是一个问题,因为列表中不能有零。
有没有更好的方法来解决它?谢谢。
【问题讨论】:
-
有没有打算编写自己的排序算法而不是使用标准的
Arrays.sort/Collections.sort? -
不,我不知道它有这样的本机功能,我试过了(Arrays.sort(numbers)),它以相同的顺序打印出数组,我查一下,谢谢。另外,它也适用于字母排序吗?
-
是的,它将与
String集合/数组一起作为其自然排序。试试看这是否是你需要的排序。
标签: java arrays sorting numbers int