简体   繁体   中英

ArrayIndexoutofbound exception merging two sorted array

I have seen other solutions like this and wondering if there is anything wrong with my approach of using for loop. I don't want to use while loop as others have used in their solution.

package com.my.practice;

public class MedianOfTwoArrays {

    public static void main(String[] args) {
        // Given two sorted arrays of same size

        int[] a1 = {1,2,3,4,5,6};
        int[] a2 = {7,8,9,10,11,12};        

        int[] mergedArray = new int[a1.length + a2.length];

        for(int i=0 ; i < a1.length; i++){
            mergedArray[i] = a1[i];
        }

        //System.out.println("Length:"+2*(a1.length));

        for(int i= a1.length; i < 2 * (a1.length); i++) {
            mergedArray[i] = a2[i];
        }

        for(int i=0 ; i < 2*(a1.length); i++){          
            System.out.println("Part of Array: "+mergedArray[i]+ " Length is: "+mergedArray.length);
        }
    }
}

I am getting following error :

Length:12
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
    at com.my.practice.MedianOfTwoArrays.main(MedianOfTwoArrays.java:30)

It's not a good idea to rely on the two arrays having the same length, so I wouldn't use a1.length * 2. In addition, you can't use the same index for the original arrays and the merged array, since the merged array is longer.

A suggested fix:

int[] mergedArray = new int[a1.length + a2.length];

for(int i=0 ; i < a1.length; i++){
    mergedArray[i] = a1[i];
}

for(int i= 0 ; i < a2.length; i++){
    mergedArray[a1.length + i] = a2[i];
}

for(int i=0 ; i < mergedArray.length; i++){
    System.out.println("Part of Array: "+mergedArray[i]+ " Length is: "+mergedArray.length);
}

The issue in your code is due to using i as an index for a2 in second loop. Its valid for mergedArray but not for a2

Either use i-a1.length as index in your second loop

for(int i= a1.length; i < 2 * (a1.length); i++) {
    mergedArray[i] = a2[i-a1.length];
}

Or use three indices: i , j & k . Just to give you an idea

int i, j, k = 0;

for (i = 0; i<a1.length; i++){
    mergedArray[k] = a1[i];
    k++;
}

for (j=0; j<a2.length; j++){
    mergedArray[k] = a2[j];
    k++;
}

In this line:

for (int i= a1.length; i < 2 * (a1.length); i++) {
    mergedArray[i] = a2[i];
}

you are trying to access a2[i] for i from 6 to 11. Since a2 is an array of size 6, a2[6] , a2[7] ... a2[11] do not exist.

In your case, you want to insert values a2[1] into mergedArray[6] , a2[2] into mergedArray[7] etc.

You either need to substract a1.length on the right side:

for (int i = a1.length; i < 2 * (a1.length); i++) {
    mergedArray[i] = a2[i - a1.length];
}

or add a1.length on the left side:

for (int i = 0; i < a1.length; i++) {
    mergedArray[i + a1.length] = a2[i];
}    

Choose the more convenient one.

Mistake (for ArrayOutOfBoundException):

    for(int i= a1.length; i < 2 * (a1.length); i++) {
        mergedArray[i] = a2[i];  //Using 'i' incorrectly to access a2[i]
    }

Correcting above:

    for(int i= 0; i < a2.length; i++) {
        mergedArray[i+a1.length] = a2[i];  //Using 'i' incorrectly to access a2[i]
    }

Reasons:

  • 'i' here will ensure that a2 is not exceeded beyond its size because i's max limit is a2.length.
  • Do not assume that a2 and a1's size would be equal. While traversing a1 using a1.length and while traversing a2, use a2.length.
  • A safety (redundant) check can be added to ensure that (i+a1.length) does not exceed mergedArray size. Redundant in this case because the mergedArray's length = a1.size + a2.size.

Problem is your are using same index for arrays of different length:

for(int i= a1.length; i < 2 * (a1.length); i++)
    mergedArray[i] = a2[i];

Here at initial, i = 6 , array bounds for a2 is 0-5 however a2[i] is a2[6] , out of bounds, which gives you the exception.

You can skip those loops, by using System.arraycopy()

 System.arraycopy(a1, 0, mergedArray,0, a1.length);
 System.arraycopy(a2, 0, mergedArray,a1.length, a2.length);

If you still wana use loop, simply use another index variable:

for(int i = 0, j = a1.length; i < (a2.length); i++, j++)
    mergedArray[j] = a2[i];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM