-1

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

redpd
  • 17
  • 1
  • 5
  • Do you have a stacktrace? Have you tried debugging the application to see where you are trying to access an index out of range? – Xerillio Apr 18 '21 at 15:43
  • 1
    Please lookup guides on how to debug a C# application in the IDE (Visual Studio or whatever) you are using. I promise you it'll be worth your while. – Xerillio Apr 18 '21 at 15:50
  • Example for Visual Studio: https://learn.microsoft.com/en-us/visualstudio/get-started/csharp/tutorial-debugger?view=vs-2019 – Xerillio Apr 18 '21 at 15:52
  • 1
    Does this answer your question? [What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?](https://stackoverflow.com/questions/20940979/what-is-an-indexoutofrangeexception-argumentoutofrangeexception-and-how-do-i-f) See also https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ – Charlieface Apr 18 '21 at 15:57

1 Answers1

1

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.