0

В методе слияния mergeArrays в условии сравнения выскакивает ошибка ArrayIndexOutOfBoundsException. Почему?

public class Main {
    public static void main(String[] args) {
    int[][] commamds =
            {{45, 31, 24, 22, 20, 17, 14, 13, 12, 10},
                    {31, 18, 15, 12, 10, 8, 6, 4, 2, 1},
                    {51, 30, 10, 9, 8, 7, 6, 5, 2, 1}};

    int[] common = mergeArrays(commamds[0], commamds[1], commamds[2]);
    for (int i = 0; i < common.length; i++) {
        System.out.print(common[i] + " ");
    }

}

public static int[] mergeArrays(int[] A, int[] B, int[] C){
    int[] res = new int[A.length+B.length+C.length];
    int ia =0,ib = 0,ic =0, ires =0;
    while(ia< A.length||ib< B.length||ic< C.length){
        if(ia==A.length&& ib==B.length){
            res[ires] = C[ic];
            ic++;
        }else if(ia == A.length&&ic == C.length){
            res[ires] = B[ib];
            ib++;
        }else if(ib == B.length&& ic == C.length){
            res[ires] = A[ia];
            ia++;
        }else if(A[ia]>=B[ib] && A[ia]>=C[ic]){**//здесь ArrayIndexOutOfBoundsException.Не пойму где ошибка.**
            res[ires] = A[ia];
            ia++;
        }else if(B[ib]>=A[ia]&&B[ib]>=C[ic]){
            res[ires] = B[ib];
            ib++;
        }else{
            res[ires] = C[ic];
            ic++;
            ires++;
        }
    }
    return res;
}

}

1 Answers1

0

Для решения данной проблемы в представленном алгоритме слияния трех массивов необходимо добавить проверки на выход индексов ia, ib, ic за пределы соответствующих входных массивов A, B, C. Также следует отдельно рассматривать случаи, когда индексы корректны для всех трёх массивов или хотя бы один из массивов был обработан полностью (и соответствующий индекс достиг допустимого максимума).

Также в представленном алгоритме есть проблема с некорректным инкрементом индекса ires в результирующем массиве.

Возможная реализация (с циклом for вместо while):

public static int[] mergeArrays(int[] A, int[] B, int[] C) {
    int[] res = new int[A.length + B.length + C.length];
for (int ia = 0, ib = 0, ic = 0, ires = 0; ires < res.length; ires++) {
    if (ia < A.length && ib < B.length && ic < C.length) {
        // искать в трёх массивах
        if (A[ia] >= B[ib]) {
            if (A[ia] >= C[ic]) {
                res[ires] = A[ia++];
            } else {
                res[ires] = C[ic++];
            }
        } else if (B[ib] >= C[ic]) {
            res[ires] = B[ib++];
        } else {
            res[ires] = C[ic++];
        }
    } else if (ia == A.length) {
        // искать в B и C
        if (ib == B.length) {
            res[ires] = C[ic++];
        } else if (ic == C.length) {
            res[ires] = B[ib++];
        } else if (B[ib] >= C[ic]) {
            res[ires] = B[ib++];
        } else {
            res[ires] = C[ic++];
        }
    } else if (ib == B.length) {
        // искать в A и C
        if (ic == C.length || A[ia] >= C[ic]) {
            res[ires] = A[ia++];
        } else {
            res[ires] = C[ic++];
        }
    } else if (B[ib] >= A[ia]) {
        res[ires] = B[ib++];
    } else {
        res[ires] = A[ia++];
    }
}
return res;

}

Nowhere Man
  • 15,995
  • 33
  • 19
  • 29
  • Спасибо за ответ! Проблема решается. Правда я до этого не знал, что res[ires] = A[ia++]; - это тоже самое, что res[ires] = A[ia]; ia++; – IliaShoo Nov 13 '22 at 19:18