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方法打印输出。我真的不知道我做错了什么。我知道大部分程序都有效,因为如果我将print命令放在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));
}
}
答案 0 :(得分:2)
您的public static void processD(Integer[] iA)
- 复制本地array
变量中的值,对该局部变量执行所有操作,但永远不会复制iA
参数中的值< /强>
当然iA
参数保持不变。
完成后,在方法结束时,只需:
for(int i=0; i<array.length; i++) {
iA[i]=array[i];
}