当前位置: 代码迷 >> java >> 完成一个交换整数数组的前半部分和后半部分的方法
  详细解决方案

完成一个交换整数数组的前半部分和后半部分的方法

热度:82   发布时间:2023-07-31 11:30:41.0

每当我尝试运行我的代码时,我总是越界错误。 有谁知道这是怎么回事? 我似乎无法弄清楚。

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;
    }
}
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 ,它已经超出范围。

您需要练习调试,放置断点并在执行时跟踪代码。

您可能已经使用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]

分配新阵列是浪费空间。 只需就地交换两半:

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;
    }
}

该代码允许奇数长度,并且将不保留中心值。

  相关解决方案