因此,我正在尝试使用递归MSD(最高有效数字)基数排序。这种目标的目的是尽快对500,000个随机整数进行排序(根据我自己生成的数字。生成的数字的范围介于0到MaxValue之间。因此,在下面的代码中,您将为整数乘以一百万当您调用该函数时)。我正在尝试使用Tasks类实现异步操作,但是由于某种原因,当我将其设置为0到9时,for循环中的计数器变量会升至10。运行代码会返回“索引不在数组的边界”,因为我可以通过计数器变量访问大小仅为10个单位的数组。这是我的MSD Radix排序功能的代码:
public static List<int> MSDRadixSort(List<int> RandommNumbers, int mult)
{
List<int>[] Buckets = new List<int>[10];
int[] RandomNumbers = RandommNumbers.ToArray();
int singleDigit = 0;
int[] temp;
Buckets[0] = new List<int>();
Buckets[1] = new List<int>();
Buckets[2] = new List<int>();
Buckets[3] = new List<int>();
Buckets[4] = new List<int>();
Buckets[5] = new List<int>();
Buckets[6] = new List<int>();
Buckets[7] = new List<int>();
Buckets[8] = new List<int>();
Buckets[9] = new List<int>();
temp = (int[])RandomNumbers.Clone();
for (int i = 0; i < temp.Length; i++)
{
temp[i] /= mult;
}
for (int i = 0; i < temp.Length; i++)
{
singleDigit = temp[i] % 10;
Buckets[singleDigit].Add(RandomNumbers[i]);
}
if (mult == 1)
{
List<int> NewList = new List<int>(SIZE);
for (int i = 0; i < 10; i++)
{
NewList.AddRange(Buckets[i]);
}
return NewList;
}
else
{
var tasks = new Task<List<int>>[10];
for (int i = 0; i < 10; i++)
{
if(Buckets[i].Count == 1)
{
continue;
}
else
{
if (mult != 1)
{
tasks[i] = Task.Run(() => MSDRadixSort(Buckets[i], mult /= 10));
}
else
{
tasks[i] = Task.Run(() => MSDRadixSort(Buckets[i], mult));
}
}
}
List<int> NewList = new List<int>(SIZE);
foreach (var task in tasks)
{
NewList.AddRange(task.Result);
}
return NewList;
}
}
给我带来麻烦的特定部分是这样的:
var tasks = new Task<List<int>>[10];
for (int i = 0; i < 10; i++)
{
if(Buckets[i].Count == 1)
{
continue;
}
else
{
if (mult != 1)
{
//This is the line where the exception happens
tasks[i] = Task.Run(() => MSDRadixSort(Buckets[i], mult /= 10));
}
else
{
tasks[i] = Task.Run(() => MSDRadixSort(Buckets[i], mult));
}
}
}
由于某种原因,发生异常时计数器变量(i)为10,我无法真正弄清楚它可能如何递增。感谢任何决定提供帮助的人!