问题描述
每当我尝试运行我的代码时,我总是越界错误。 有谁知道这是怎么回事? 我似乎无法弄清楚。
public class Swapper{
/**
This method swaps the first and second half of the given array.
@param values an array
*/
public void swapFirstAndSecondHalf(int[] values) {
// your work here
int[] first = new int[values.length/2];
int[] second = new int[values.length/2];
for(int i = 0; i < values.length / 2; i++) {
second[i] = values[i];
}
for (int j = values.length / 2; j < values.length; j++) {
first[j] = values[j];
}
for(int k = 0; k < values.length / 2; k++) {
values[k] = first[k];
}
for(int l = values.length / 2; l < values.length; l++) {
values[l] = second[l];
}
}
// This method is used to check your work
public int[] check(int[] values) {
swapFirstAndSecondHalf(values);
return values;
}
}
1楼
int[] first = new int[values.length/2];
因此索引[0..values.length/2 - 1]
对first
有效。
for (int j=values.length/2; j<values.length; j++)
{
first[j] = values[j];
}
所以j
的第一个值是values.length/2
,它已经超出范围。
您需要练习调试,放置断点并在执行时跟踪代码。
2楼
您可能已经使用System.arraycopy()
而不是所有的for
循环。
public static void main(String[] args) throws Exception {
int[] values = {1, 2, 3, 4, 5};
values = swapFirstAndSecondHalf(values);
System.out.println(Arrays.toString(values));
values = new int[]{1, 2, 3, 4, 5, 6};
values = swapFirstAndSecondHalf(values);
System.out.println(Arrays.toString(values));
}
public static int[] swapFirstAndSecondHalf(int[] values) {
boolean evenSize = values.length % 2 == 0;
int half = values.length / 2;
int[] swapper = new int[values.length];
System.arraycopy(values, evenSize ? half : half + 1, swapper, 0, half);
System.arraycopy(values, 0, swapper, evenSize ? half : half + 1, half);
// The middle number stays the middle number
if (!evenSize) {
swapper[half] = values[half];
}
return swapper;
}
结果:
[4, 5, 3, 1, 2]
[4, 5, 6, 1, 2, 3]
如果您希望将中间数字(奇数大小的数组)作为下半部分的一部分,那么swapFirstAndSecondHalf()
看起来将像这样:
public static int[] swapFirstAndSecondHalf(int[] values) {
boolean evenSize = values.length % 2 == 0;
int half = values.length / 2;
int[] swapper = new int[values.length];
System.arraycopy(values, half, swapper, 0, evenSize ? half : half + 1);
System.arraycopy(values, 0, swapper, evenSize ? half : half + 1, half);
return swapper;
}
结果:
[4, 5, 3, 1, 2]
[4, 5, 6, 1, 2, 3]
3楼
分配新阵列是浪费空间。 只需就地交换两半:
public static void swapFirstAndSecondHalf(int[] values) {
final int len = values.length / 2;
final int offset = values.length - len;
for (int i = 0; i < len; i++) {
int temp = values[i];
values[i] = values[offset + i];
values[offset + i] = temp;
}
}
该代码允许奇数长度,并且将不保留中心值。