-2

So I was trying to run the following code which is to merge two sorted arrays into one sorted array. However it keeps giving me an arrayIndexOutOfBound exception. I want to prevent that exception.

public class SortArray {

    public static void main(String[] args){
        SortArray sa = new SortArray();
        // create two arrays
        int[] a = {1, 2, 3, 4, 5};
        int[] b = {6, 7, 8, 9, 10};
        int[] merge = sa.mergeArray(a, b);
        for (int i = 0; i < merge.length; i++) {
            System.out.print(merge[i] + " ");
        }

    }       
    public int[] mergeArray(int[] arr1, int[] arr2){
        int arr1Length = arr1.length;
        int arr2Length = arr2.length;
        int[] merge = {}; // the merged array
        int i, j;
        int k = 0;
        // when the index of both arrays are within array length
        for (i = 0, j = 0; i < arr1.length && j < arr2Length;) {
            if (arr1[i] < arr2[j]) {
                merge[k] = arr1[i];
                i++;
                k++;
            }else if (arr1[i] > arr2[j]) {
                merge[k] = arr2[j];
                j++;
                k++;
            }
        }
        // when arra1 is the remaining array
        if (i < arr1Length) {
            merge[k] = arr1[i];
            i++;
            k++;
        }
        // when array2 is the remaining error
        if (j < arr2Length) {
            merge[k] = arr2[j];
            j++;
            k++;    
        }
        return merge;
    }

}

Can anybody help me? Thanks!

Mizuki
  • 2,153
  • 1
  • 17
  • 29
red_Coder
  • 95
  • 2
  • 6

1 Answers1

1

You aren't sizing the merge array correctly.

int[] merge = {};

creates a zero length int[] (and Java arrays have a fixed length). You want something like

int[] merge = new int[arr1Length + arr2Length];
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • Thanks! As I'm new here, I apologize to everyone who thinks the editing of my question is very inappropriate. I will improve later! – red_Coder Mar 31 '16 at 04:43