Search code examples
c#bubble-sortindexoutofrangeexception

indexOutofRange BubbleSort when using inputbox


Its been bugging me for hours because it is always returning 0 at numbers[i] and I cant figure out the problem. code worked for a different program but I had to change it so it could have a custom array size and that's when everything went wrong. any help would be great. Thanks in advance.

int[] numbers = new int[Convert.ToInt16(TxtArray.Text)];
int j = 0;
for (j = numbers.Length; j >= 0; j--)
{
    int i = 0;
    for (i = 0; i <= j - 1; i++)
    {
        string NumbersInput = Microsoft.VisualBasic.Interaction.InputBox("Enter Numbers to be sorted",
                "Numbers Input", "", -1, -1);
        numbers[i] = Convert.ToInt16(NumbersInput);     
       //returns 0 in if statement
        if (numbers[i] < numbers[i + 1])
        {           
            int intTemp = 0;
            intTemp = numbers[i];
            numbers[i] = numbers[i + 1];
            numbers[i + 1] = intTemp;
        }
    }
}

for (int i = 0; i < numbers.Length; i++)
{
    LstNumbers.Items.Add(numbers[i]);
}

Solution

  •  private void button1_Click(object sender, EventArgs e)
    {
      int sizeOfArrayInt = Convert.ToInt32(arraySize.Text);
      int[] array = new int[sizeOfArrayInt];
      string numbers = arrayValues.Text;
      string[] numbersSplit = numbers.Split(',');
    
      int count = 0;
      foreach (string character in numbersSplit)
      {
        int value;
        bool parse = Int32.TryParse(character, out value);
        if (value != null)
        {
          array[count] = value;
        }
    
        count++;
      }
    
      array = this.SortArray(array);
      foreach (int item in array)
      {
        this.listBox.Items.Add(item);
      }
    }
    
    private int[] SortArray(int[] arrayToSort)
    {
      //int[] sortedArray = new int[arrayToSort.Length];
      int count = arrayToSort.Length;
      for (int j = count; j >= 0; j--)
      {
        int i = 0;
        for (i = 0; i <= j - 2; i++)
        {
          if (arrayToSort[i] < arrayToSort[i + 1])
          {
            int intTemp = 0;
            intTemp = arrayToSort[i];
            arrayToSort[i] = arrayToSort[i + 1];
            arrayToSort[i + 1] = intTemp;
          }
        }
      }
    
      return arrayToSort;
    }
    

    strong text

    This I got to work as a Windows Form and the output displays in the list box as each array item or individual i iteration over the array. Of course there is no error checking. Hope that helps.