【发布时间】:2016-12-07 03:55:27
【问题描述】:
public static void main(String[] args) {
Integer[] ar = new Integer[] { 5, 2, 1, 12, 2, 10, 4, 13, 5 };
processD(ar);
System.out.println("Sorted: " + Arrays.toString(ar));
}
我基本上是在尝试将Integer[] 移动到processD 方法,然后通过main 方法打印回输出。我真的不知道我做错了什么。我知道大多数程序都可以正常工作,因为如果我将打印命令放在processD 函数中,它就可以完美运行。但在 main 方法中,它只是打印输入而不处理它。任何帮助将不胜感激。谢谢
public class MethodBeta {
public static void processD(Integer[] iA) {
int[] array = new int[iA.length];
for (int u = 0; u < iA.length; u++) {
array[u] = iA[u].intValue();
}
// If array is smaller than 2 then already sorted
if (array.length < 2) {
return;
}
// create sub-arrays and keep multiplying by 2 to increase their number
int z1 = 1;
int z2, z3;
while (z1 < array.length) {
z2 = 0;
z3 = z1;
while (z3 + z1 <= array.length) {
merge(array, z2, z2 + z1, z3, z3 + z1);
z2 = z3 + z1;
z3 = z2 + z1;
}
if (z3 < array.length) {
merge(array, z2, z2 + z1, z3, array.length);
}
z1 *= 2;
}
}
public static void merge(int[] ar1, int startL, int stopL, int startR, int stopR) {
int[] right = new int[stopR - startR + 1];
int[] left = new int[stopL - startL + 1];
for (int i = 0, k = startR; i < (right.length - 1); ++i, ++k) {
right[i] = ar1[k];
}
for (int i = 0, k = startL; i < (left.length - 1); ++i, ++k) {
left[i] = ar1[k];
}
right[right.length - 1] = Integer.MAX_VALUE;
left[left.length - 1] = Integer.MAX_VALUE;
for (int z = startL, x = 0, y = 0; z < stopR; ++z) {
if (left[x] <= right[y]) {
ar1[z] = left[x];
x++;
} else {
ar1[z] = right[y];
y++;
}
}
}
public static void main(String[] args) {
Integer[] ar = new Integer[] { 10, 9, 8, 7, 2, 10, 4, 13, 5 };
processD(ar);
System.out.println("Sorted: " + Arrays.toString(ar));
}
}
【问题讨论】:
-
你在
processD(ar);做什么?可以展示一下吗? -
我需要在 main 方法中添加打印功能。那么实现这一点的最佳方法是什么?而processD基本上就是一个通过数组的排序过程……
-
@AndrewLi 对象的值是它的引用。 Integer[] 的工作方式相同,所以我相信实际的数组会改变?
-
我认为这里可能存在问题: public static void mergeSortB(Integer[] inputArray){ int[] array = new int[inputArray.length]; for (int m = 0; m