Java 尝试进行合并排序,索引超出范围

Java 尝试进行合并排序,索引超出范围,java,mergesort,Java,Mergesort,我正试着做这件事。当我运行测试时。它说我的索引超出了范围。我错过了什么错误吗 错误为:java.lang.ArrayIndexOutOfBoundsException:索引3超出长度3的界限 public static void mergeSort(int[] a) { int[] L = null; int[] R = null; if (a.length < 2) return; L = new int[a.length / 2];

我正试着做这件事。当我运行测试时。它说我的索引超出了范围。我错过了什么错误吗

错误为:
java.lang.ArrayIndexOutOfBoundsException:索引3超出长度3的界限

public static void mergeSort(int[] a) {
    int[] L = null; 
    int[] R = null; 

    if (a.length < 2)
        return;
    L = new int[a.length / 2];
    R = new int[a.length - a.length / 2];
    int x = 0;
    for (int y = 0; y < a.length; y++) {
        if (y < a.length) {
            L[y] = a[y];
        } else {
            R[x] = a[y];
            x += 1;
        }
    }
    mergeSort(L);
    mergeSort(R);
    merge(a, L, R); 
}

public static void merge(int[] a, int[] L, int[] R) {
    tracker.calltracking(a, L, R);
    int x = 0, y = 0, z = 0;
    while (x < L.length && y < R.length) {
        if (L[x] < R[y]) {
            a[z++] = L[x++];
        } else {
            a[z++] = R[y++];
        }
    }
    while (x < L.length) {
        a[z++] = L[x++];
    }
    while (z < R.length) {
        a[z++] = R[y++];
    }
}
公共静态无效合并排序(int[]a){
int[]L=null;
int[]R=null;
如果(a.长度<2)
返回;
L=新整数[a.长度/2];
R=新整数[a.length-a.length/2];
int x=0;
对于(int y=0;y
让我们调试长度为3的mergeSort方法

L用大小1初始化,R用大小2初始化

您将进入循环

第一次迭代:y为0,y小于a.length


第二次迭代:y为1,y小于a.length。哎呀!索引1中的L超出边界。

复制循环中的测试不正确:您将所有元素复制到
L
数组,该数组应只接收左半部分

您应该使用两个单独的循环,而不是在每次迭代时进行测试:

public static void mergeSort(int[] a) {
    if (a.length >= 2) {
        int nL = a.length / 2;
        int nR = a.length - nL;
        int[] L = new int[nL];
        int[] R = new int[nR];

        for (int x = 0; x < nL; x++) {
            L[x] = a[x];
        }
        for (int x = 0; x < nR; x++) {
            L[x] = a[nL + x];
        }
        mergeSort(L);
        mergeSort(R);
        merge(a, L, R);
    }
}
公共静态无效合并排序(int[]a){
如果(a.长度>=2){
int nL=a.长度/2;
int nR=a.长度-nL;
int[]L=新的int[nL];
int[]R=新的int[nR];
对于(int x=0;x