-1

I get an error out of bounds in my second for loop. Any advice on what I'm doin wrong? Maybe I didn't make the array big enough?

private static void mergeSort(int length, int[] arr) {
    if (length>1)
    {
        int h = (int) Math.floor(length/2);
        int m = length-h;
        int[] U= new int[h];
        int[] V=new int[m];

        for(int i=0; i<h; i++){
            U[i]=arr[i];
        }
        for(int i=h; i<length; i++){
            V[i]=arr[i];
        }
        mergeSort( h , U);
        mergeSort(m ,V);
        merge(h , m , U , V, arr);
    }
  • 1
    Please read: [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – Turing85 Mar 18 '21 at 21:13

1 Answers1

1
    for(int i=h; i<length; i++){
        V[i]=arr[i];
    }

You expect V to be 'length' long after having allocated it as less than that.

    int m = length-h;

    int[] V=new int[m];

But I second the suggestion, in comments, that you learn a little debugging skill.

user15187356
  • 807
  • 3
  • 3