大家晚上好!我创建了一个桶排序算法,但它给我一个索引超出范围的错误。你能告诉我问题出在哪里吗?我自己找不到解决方案,这就是我寻求您的帮助的原因
public int[] Sort(int[] unsortedSequence)
{
List<List<int>> buckets = new List<List<int>>();
InitializeBuckets(buckets);
Scatter(unsortedSequence, buckets);
int i = 0;
foreach (List<int> bucket in buckets)
{
int[] arr = bucket.ToArray();
InsertionSort(arr);
foreach (int d in arr)
{
unsortedSequence[i++] = d;
}
}
return unsortedSequence;
}
private static void Scatter(int[] array, List<List<int>> buckets)
{
foreach (int value in array)
{
int bucketNumber = GetBucketNumber(value);
buckets[bucketNumber].Add(value);
}
}
private static void InsertionSort(int[] array)
{
int j;
int temp;
for (int i = 1; i < array.Length; i++)
{
j = i;
while (j > 0 && array[j] < array[j - 1])
{
temp = array[j];
array[j] = array[j - 1];
array[j - 1] = temp;
j--;
}
}
}
private static int GetBucketNumber(int value)
{
int val = value * 10;
return val;
}
private static void InitializeBuckets(List<List<int>> buckets)
{
for (int i = 0; i < 10; i++)
{
List<int> a = new List<int>();
buckets.Add(a);
}
}
慕的地6264312
qq_花开花谢_0
相关分类