Search code examples
c#sortingmergesort

MergeSort Algorithm "IndexOutOfRangeException"


I've been reading the Introduction to Algorithms and tried to implement the pseudocode, but I can't seem to pinpoint what is causing IndexOutOfRangeException.

Merge

The error happens at left[i] < right[j]

static void Merge(int[] array, int start, int middle, int end)
{
    i = 1;
    j = 1;

    for (k = start; k < end; k++)
    {
        if (left[i] < right[j])
        {
            array[k] = left[i];
            i = i + 1; // -> i++;
        }
        else
        {
            array[k] = right[j];
            j = j + 1; // -> j++;
        }
    }
}

Solved

I solved it by setting all i and j variables to 0 and k to k = start - 1


Solution

  • You are getting error in this line:

    if (left[i] < right[j])

    since i exceeds left array length when it becomes 6 and array left has only 6 elements.

    It is very easy to figure it out when you use debugging.