jbeverid
jbeverid

Reputation: 288

Arraycopy Crashing My Program

I am working on a homework assignment where I have to implement a MergeSort based on the author of our books psuedo-code. (Foundations of Algorithms, 4th ed by Neapolitan and Naimipour).

From the main method I am calling mergeSort with the int n being the length of the array and S[] being the array needing to be sorted. S[] is already filled with random numbers between 1 and 999. My program is crashing at the last arraycopy in merge and I am not sure why it is and I have tried debugging in netbeans. I feel like this is probably a dumb mistake that I just can't see. Any help would be great. Thanks in advanced.

public static void mergesort (int n, int S[])
   {
      if(n>1){
         final int h=n/2, m=n-h;
         int U[] = new int[h];
         int V[] = new int[m];
         System.arraycopy(S, 0, U, 0, h);
         System.arraycopy(S, h, V, 0, m);
         mergesort(h, U);
         mergesort(m, V);
         merge(h, m, U, V, S);
      }
   }
   public static void merge(int h, int m, final int U[], final int V[], final int S[])
   {
      int i=0, j=0, k=0;
      while(i<h && j<m){
         if(U[i]<V[j]) {
            S[k] = U[i];
            i++;
         }
         else {
            S[k]=V[j];
            j++;
         }
         k++;
      }
      if(i>h)
         System.arraycopy(V, j, S, k, h+m);
      else
         System.arraycopy(U, i, S, k, h+m);
   }

EDIT: I realized I had a couple small mistakes in merge. The biggest changes were changing comparisons to work with equals and also understanding the length in arraycopy is the number of elements I want to copy. Here is my merge method. mergesort stayed the same.

   public static void merge(int h, int m, final int U[], final int V[], int S[])
   {
      int i=0, j=0, k=0;
      while(i<h && j<m){
         if(U[i]<V[j]) {
            S[k] = U[i];
            i++;
         }
         else {
            S[k]=V[j];
            j++;
         }
         k++;
      }
      if(i>=h)
         System.arraycopy(V, j, S, k, m-j);
      else
         System.arraycopy(U, i, S, k, h-i);
   }

Thanks for the help.

Upvotes: 1

Views: 577

Answers (1)

Maarten Kesselaers
Maarten Kesselaers

Reputation: 1251

Tested it. It as an IndexOutOfBounds. The reason is that the length that you give in the ArrayCopy is greater than the count off your source-Array.

Upvotes: 3

Related Questions