0

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;
          }
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
waldorick
  • 15
  • 2
  • 1
    if `2500` is the size of the collection, the condition in the `for` should be `i < 2500 - 1;`: `for (int i = 0; i < 2500 - 1; i++) {...}` – Dmitry Bychenko Dec 28 '17 at 14:15
  • What is the value of `i` when the exception is thrown and how many entries are there in `szamok`? Some simple debugging should tell you what your invalid index is which will then allow you to identify where your problem comes from. – Chris Dec 28 '17 at 14:15
  • 2
    If you have 2500 items in an array then they appear at indexes 0-2499. What indexes does your code generate the last time through its loop when `i` = 2499? – Damien_The_Unbeliever Dec 28 '17 at 14:15

1 Answers1

0

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++)

mode777
  • 3,037
  • 2
  • 23
  • 34