I'm having a problem with getting this code (from Rosetta Code) to work as part of a greater Windows Form Project:
It's a plain old insertion sort. Where it's going wrong is the bit involving the second for loop (The numbers generate just fine), in the sorting part of it. To me within a couple of iterations of the loop then j will be into negative figures and whilst other languages such as Javascript and Pascal don't seem to mind this...C# isn't happy.
private void button3_Click(object sender, EventArgs e)
{
int i, j, k;
int[] a = new int[12];
Random randomObject = new Random();
ClearOutputs(); // this is an event which just clears the
text
from the text boxes.
//Generate some random numbers
for (i = 0; i < a.Length; i++)
{
a[i] = randomObject.Next(1, 1000);
textBox1.AppendText(a[i].ToString() + "\n");
}
for (i = 1; i <= a.Length; i++)
{
k = a[i];
//*******************
for (j = i; j > 0 & k < a[j - 1]; j--)
{
a[j] = a[j - 1];
a[j] = k;
}
}
// ***************
//Display them...it never executes this part.
for (i = 0; i < a.Length; i++)
{
textBox2.AppendText(a[i].ToString() + "\n");
}
}
The longer term fix would be for me to understand the coding of the algorithm...and then fix it for myself, but if anyone could point me in the right direction...I've tried setting the 'for' loop at a higher initial value and yet still got the same "System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'" Any help would be greatly appreciated.