System.arraycopy 抛出 ArrayIndexOutOfBoundsException

System.arraycopy throw ArrayIndexOutOfBoundsException

为什么 System.arraycopy() 抛出 ArrayIndexOutOfBoundsException?我正在尝试编写合并排序(这不是最终版本,首先我希望当前算法可以处理这些数据)。

package Procedural.Intro;

import java.util.Arrays;
import java.util.Random;

/**
 * Created by Сергей on 28.06.2015.
 */
public class MergerSort {

    public static void main(String[] args) {

        int [] initial;
        int [] initial2;


        initial = new int [] {1, 4, 5, 6, 7};
        initial2 = new int [] {2, 4, 9, 11, 121};



        System.out.println("Array1 initial: " + Arrays.toString(initial));
        System.out.println("Array2 initial: " + Arrays.toString(initial2));


        System.out.println("Array result: " + Arrays.toString(MergerSort.mergerSort(initial, initial2)));



    }
       private static int [] mergerSort(int[] left, int[] right) {

            int [] result = new int[left.length + right.length];
            int leftIndex = 0;
           int rightIndex = 0;
          while( leftIndex + rightIndex < result.length) {

               if(left[leftIndex] > right[rightIndex]) {
                   result[leftIndex + rightIndex] = right[rightIndex++];
               }
               else {
                   result[leftIndex + rightIndex] = left[leftIndex++];
               }
               if(leftIndex == left.length) {

                 System.arraycopy(right, right[rightIndex],  result, leftIndex + rightIndex, result.length - (leftIndex + rightIndex));
                   break;
               }
               if(rightIndex == right.length) {
                   System.arraycopy(left, left[leftIndex],  result, leftIndex + rightIndex, result.length - ( leftIndex + rightIndex));
                   break;
               }
           }

         return result;
        }

}

您忘记了最后一个索引不是数组长度,它是数组长度 - 1。您忘记从 System.arraycopy
中的最后一个参数中减去一个 你有 result.length - (leftIndex + rightIndex) 它应该在的地方 result.length - (leftIndex + rightIndex) - 1

如果您查看 System.arrayCopy 的文档,它期望数组中的 index 作为第二个参数。但是,您的数组中有一个 value。所以很可能你想写

System.arraycopy(right, rightIndex, ...

而不是

System.arraycopy(right, right[rightIndex], ...

第二次调用 System.arraycopy

也是如此