【发布时间】:2021-03-29 11:47:27
【问题描述】:
在过去的几天里,我一直在自己练习如何对 Java 数组进行排序。我想对我现在连接的数组从最小到最大进行排序。我很挣扎,需要指导。有人可以向我解释我做错了什么吗?我想从我目前的错误中吸取教训。
代码:
public static void main(String[] args) {
// merge these arrays: ([0,3,4,31],[4,6,30])
// process below is to create an array to fit the lengths of arr3 and 4
int[] arr3 = { 0, 3, 4, 31 };
int[] arr4 = { 4, 6, 30 };
int[] arr5 = new int[arr3.length + arr4.length];
// this loop gets the first indices of arr3
for (int i = 0; i < arr3.length; i++) {
arr5[i] = arr3[i];
}
// this array concat elements of arr4
for (int k = 0; k < arr4.length; k++) {
arr5[arr3.length + k] = arr4[k]; //
}
int small = 0;
int large = arr5.length - 1;
for (int f = 0; f < arr5.length; f++) {
if (arr5[f] < arr5[small]) {
arr5[small] = arr5[f];
small++;
} else {
arr5[large] = arr5[f];
large--;
}
}
// prints out the new array
System.out.println(Arrays.toString(arr5));
}
}
我试图在输出控制台中获得的输出:
[0,3,4,4,6,30,31]
我得到的是什么:
[0, 3, 4, 31, 4, 3, 0]
【问题讨论】: