Search code examples
c#bubble-sort

C# Bubble sort error?


What's the problem here? I have a block with 2500 random number and i want to sort them with bubble sort. But when I run the program I've got this:

System.IndexOutOfRangeException

error code after this:

if (szamok[i] > szamok[i + 1]).

(Sorry for bad English :/)

        int r = 2500;
        int seged;


        while (r > 1)
          {
              for (int i = 0; i < 2500; i++)
               {
                if (szamok[i] > szamok[i + 1])
                  {
                    seged = szamok[i + 1];
                    szamok[i + 1] = szamok[i];
                    szamok[i] = seged;
                   }

               }
            r = r - 1;
          }

Solution

  • The error says it: Your index is out of range. You are trying to access an element in your array after the last element in this array.

    The line szamok[i] > szamok[i + 1] seems to be the culprit. +1 is one too many.

    Try changing you loop so you don't visit the last element but only the second to last:

    for (int i = 0; i < (2500-1); i++)