1

I'm trying to create a non-recursive version of MergeSort but for some reason merge is keeping the code from running in its entirety.

Mergesort Code:

public void mergeSort(int[] input)
{

    int n = input.length;
    int size;
    int l;
    for (size = 1; size <= n-1; size = 2*size)
    {
        for (l = 0; l < n-1; l += 2*size)
        {
            int m = l + size -1;
            int r = minimum(l + 2*size - 1, n-1);
            merge(input, l, m, r);
        }
    }       
}

Merge code:

public static void merge(int[] numbers, int low, int middle, int high)
{

    // Copy both parts into the helper array
     int helper[];
    helper = new int[numbers.length];

   for (int i = low; i <= high; i++) {
       helper[i] = numbers[i];
   }


   int i = low;
   int j = middle + 1;
   int k = low;
   // Copy the smallest values from either the left or the right side back
   // to the original array

   while (i <= middle && j <= high) {
       if (helper[i] <= helper[j]) {
            numbers[k] = helper[i];
            i++;
       } else {
            numbers[k] = helper[j];
            j++;
       }

       k++;
     }
     // Copy the rest of the left side of the array into the target array

     while (i <= middle) {
           numbers[k] = helper[i];
           k++;
           i++;
     }
 }

This is how I fill up the input array (which is of size 100):

public static int fillArray()
{
    Random r = new Random();
    int rand = r.nextInt();
    return rand;
}
 //followed by these lines of code in the main method:

    int[] arr;

    arr = new int[100];

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

The exception is with numbers[k] = helper[i] in merge().

I know that the contents of the input array are fine because I print out the contents of the array before I perform MergeSort on it. Does anyone know what the problem is?

Codebender
  • 14,221
  • 7
  • 48
  • 85
Maria-Andersado
  • 777
  • 1
  • 9
  • 18

2 Answers2

0

You didn't mention what exception you get but I assume its array out of bounds. What prevents your middle variable from exceeding the size of the array?

while (i <= middle) {
   numbers[k] = helper[i];
   k++;
   i++;
}

Put in debugging prints etc.

HulkSmash
  • 386
  • 1
  • 6
0

Fix the m in mergeSort() like this:

int m = Math.min(l + size - 1, n - 1);
Cinnam
  • 1,892
  • 1
  • 15
  • 23
  • This solved the issue entirely, thank you. Can you explain why my m caused the program to slip up, but this one works fine? – Maria-Andersado Sep 14 '15 at 05:08
  • Because both `l` and `size` can be almost as big as `n` - you need to limit their sum just like you do with `r` – Cinnam Sep 14 '15 at 05:15