I am learning about sorting algorithms, and am currently at a loss with my first "Distribution Pass". As my notations describe, the first loop is where I sort each value into my bucket array based on the one's value. It works for every value except for the 9th index of my values array. The loop terminates before it gets to the 9th index. I've tried changing the conditions of the for loop, but that doesn't seem to work. Some help or hints as to what is happening would be much appreciated!
** Edit this is not the complete algorithm, it is only the first two steps. I am following the instructions from my c# book. The notes placed before each loop are the word for word instructions from the book. I don't want to continue with the sorting algorithm until I get the first loop working properly.
public static void Sort(int[] values)
{
int n = values.Length;
int[,] buckets = new int[n, n - 1];
int index = 0;
// Place each value of the one-dimensional array
// into a row of the bucket array, based on the
// value's "one's" (rightmost) digit.
// "Distribution Pass"
for (int i = 0; i < values.Length -1; ++i)
{
// Get the one's value of values[i]
int ones = (values[i] % 10);
// Place the value in the appropriate bucket
buckets[ones, i] = values[i];
}
// Loop through the bucket array row by row,
// and copy the values back to the original
// array.
// "Gathering Pass"
for (int r = 0; r < n; r++)
{
for (int c = 0; c < n - 1; c++)
{
try
{
if (buckets[r, c] != 0)
{
values[index] = buckets[r, c];
index++;
}
}
catch
{
}
}
}
}
private void button1_Click(object sender, EventArgs e)
{
Random rand = new Random();
int[] randomArray = new int[10];
label1.Text = "Unsorted Array: ";
label2.Text = " Sorted Array: ";
for (int i = 0; i < randomArray.Length; i++)
{
randomArray[i] = rand.Next(10, 100);
label1.Text += randomArray[i] + " ";
}
Sort(randomArray);
label2.Text += string.Join(" ", randomArray);
}