-9

I'm doing a programming task for my course and I've been challenged to do it in C#. When I run it, it highlights numbers[position+1] and gives me the error: System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {

            // array of numbers
            int[] numbers = { 9, 5, 4, 15, 3, 8, 11, 2 };

            int noOfNumbers = 8;

            int temp;

            while (noOfNumbers > 1) {

                foreach(int position in numbers) {

                    if (numbers[position] > numbers[position+1])
                    {

                        temp = numbers[position];

                        numbers[position] = numbers[position + 1];

                        numbers[position + 1] = temp;

                    }

                }
                noOfNumbers = noOfNumbers + 1;

            }

            Console.WriteLine(numbers);


        }
    }
}

Here is the pseudocode:

BEGIN
Numbers=[9,5,4,15,3,8,11,2]
AmountOfNumbers=8
Temp=0
WHILE AmountOfNumbers>1
    FOR each itemPositionInArray in Numbers
        IF Numbers[ItemPositionInArray] > Numbers[ItemPositionInArray+1]
            Temp=Numbers[ItemPositionInArray]
            Numbers[ItemPositionInArray]=Numbers[ItemPositionInArray+1]
            Numbers[ItemPositionInArry+1]=Temp
    AmountOfNumbers=AmountOfNumbers-1
OUTPUT(Numbers)
END
Adam
  • 77
  • 10
  • 4
    `foreach(int position in numbers) {` This doesn't loop over their *positions*, it loops over the numbers *themselves*. The value `position` takes on the first iteration of the loop will be 9, not 0. –  Jan 31 '20 at 15:20
  • The duplicate explains what that error means. Then if you start to use the debugger you will see that the first _position_ is equal to 9 and this, of course, is _out of range_ when you use it as it was an index into the numbers array – Steve Jan 31 '20 at 15:22
  • Change `foreach(int position in numbers)` to `for (int position = 0; position < numbers.Length; position++)` – Rand Random Jan 31 '20 at 15:23
  • For a bubblesort, you should use a boolean to check if something is changed. Inside the `if (numbers[position] > numbers[position+1])`, if nothing is swapped, you're ready – Jeroen van Langen Jan 31 '20 at 15:25
  • @RandRandom that will crash as well – Steve Jan 31 '20 at 15:25
  • @Steve - yeah, but I thought `position+1` would make more sense for OP that way – Rand Random Jan 31 '20 at 15:26
  • Also there is another big problem here. The while loop is an infinite loop. – Steve Jan 31 '20 at 15:27
  • 1
    @Steve - maybe reopen to help OP to fix all the problems, and not only the problem at hand? – Rand Random Jan 31 '20 at 15:28
  • @RandRandom OP didn't ask about other problems. OP asked about index out of range exceptions, which is a duplicate. If OP has other problems they want resolved, they should ask a separate question. – TylerH Jan 31 '20 at 15:48
  • @TylerH - not quite right, OP has `How to Bubble sort in C#?` in this question title. – Rand Random Jan 31 '20 at 15:57
  • Sure, but that's also a duplicate of [this](https://stackoverflow.com/questions/23310345/bubble-sort-in-c-sharp), [this](https://stackoverflow.com/questions/1595244/whats-the-most-elegant-way-to-bubble-sort-in-c), [this](https://stackoverflow.com/questions/14768010/simple-bubble-sort-c-sharp), and I'm sure many more. – TylerH Jan 31 '20 at 16:03

1 Answers1

4

The problem in your code is here: (like Amy said)

foreach(int position in numbers) {
    if (numbers[position] > numbers[position+1])

You're using the position as index to the array. The foreach will enumerate your array and will put in the element values into the position variable, not the index. So the first iteration position will contain 9 (not index 0)

For this you should use the "normal" for-loop.

for(int i=0; i < count; i++) { }

Here's an example to do a bubblesort. I've written some comment to explain what it does.

using System;

public class Program
{
    public static void Main()
    {
        // array of numbers
        int[] numbers = { 9, 5, 4, 15, 3, 8, 11, 2 };

        // declare a boolean.
        bool done;

        do
        {
            // when nothing happens, you're done.
            done = true;

            // create a for-loop to iterate all item-1 (except the last)
            for(int position=0;position<numbers.Length-1;position++)
            {
                // compare the values in the array
                if (numbers[position] > numbers[position+1])
                {
                    // swap the values
                    int temp = numbers[position];

                    numbers[position] = numbers[position + 1];

                    numbers[position + 1] = temp;

                    // if something was swapped, you're not ready.
                    done = false;
                }
            }

            // loop until done is set.
        } while (!done);

        Console.WriteLine(string.Join(",", numbers));
    }
}

Here's an .NET Fiddle

Jeroen van Langen
  • 21,446
  • 3
  • 42
  • 57