Search code examples
c#algorithmmergesort

Problems with my MergeSort Algorithm C#


using System;

namespace MergeSort
{
    class Program
    {
        static int[] vektor = { 5, 7, 8, 9, 1, 2, 23, 4 };
        static int[] delVektor;
        static int counter = 0;

        static void Main(string[] args)
        {
            PrintVektor(vektor);
            Merge(0, vektor.Length - 1);
            Console.WriteLine("--------");
            PrintVektor(vektor);
            Console.ReadKey();
        }

        static void PrintVektor(int[] vektor)
        {
            foreach (var item in vektor)
            {
                Console.WriteLine(item.ToString() + " ");
            }
        }

        static void Merge(int start, int stop)
        {
            if (start >= stop)
                return;

            int middle = (start + stop) / 2;

            Merge(start, middle);
            Merge(middle + 1, stop);

            delVektor = new int[stop - start + 1];

            int indexStart = start;
            int indexStop = middle + 1;

            while (indexStart <= middle && indexStop <= stop)
            {
                if (vektor[indexStart] < vektor[indexStop])
                {
                    delVektor[counter] = vektor[indexStart];
                    indexStart++;
                    counter++;
                }

                else
                {
                    delVektor[counter] = vektor[indexStop];
                    indexStop++;
                    counter++;
                }
            }

            while (indexStart <= middle)
            {
                delVektor[counter] = vektor[indexStart];
                indexStart++;
                counter++;
            }

            while (middle <= stop)
            {
                delVektor[counter] = vektor[indexStop]; // <---- here i get index out of range
                indexStop++;
                counter++;
            }

            for (int i = 0; i <= delVektor.Length - 1; i++)
            {
                vektor[start + i] = delVektor[i];
            }
        }
    }
}

The thing is i get an index out of range exception( i have commented in the code),

while (middle <= stop) {
  delVektor[counter] = vektor[indexStop]; // <---- here i get index out of range
  indexStop++; counter++;
}

I cant figure it out

I do not know what I am doing wrong. I have been staring at this code for so long now that i just want to throw the computer out of the window as soon as I try to fix it.


Solution

  • When you are using an index into an array and you increment that index you need to test whether that index is actually within the bounds of the array (0-based indexes for you code).

    Do you test your index ensuring that it cannot run out of bounds?