0

I'm currently attempting to make a Bubble Sort system in C# and to do this I need to be able to take a value out of an array based on its position. However, when I put int a = (array[0]) which should give me the 1st value in the array, I instead get a different value, often the 3rd? Please help me find my code copied below!

using System;
public class Bubble_Sort
{
    public static void Main(string[] args)
    {
        int[] numbers = new int[] { 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        int i = (numbers[0]);
        Console.WriteLine(numbers[i]);
        int a = (numbers[7]);
        Console.WriteLine(numbers[a]);
        Console.Read();
    }
}

Any help is appreciated, this is really doing my head in!

Alec Knapper.

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
  • 2
    `i = numbers[0]` therefore `i = 2` therefore in `Console.WriteLine` you try to access `numbers[2]` which holds `4`. `a = numbers[7]` therefore `a = 9` therefore in `Console.WriteLine` you try to access `numbers[9]`, which doesn't exist because the size of the array is only 9, therefore you have an indexable range of 0 to 8 inclusive. Using values from an array as indexes to access another part of the array seems a bit weird anyway. Perhaps there's a mistake in your logic? – ProgrammingLlama Sep 27 '21 at 09:50
  • Maybe a good opportunity to learn how to use the [debugger](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – Klaus Gütter Sep 27 '21 at 10:11

0 Answers0