【发布时间】:2011-04-14 21:08:41
【问题描述】:
我听说了计数排序,并根据我的理解编写了我的版本。
public void my_counting_sort(int[] arr)
{
int range = 100;
int[] count = new int[range];
for (int i = 0; i < arr.Length; i++) count[arr[i]]++;
int index = 0;
for (int i = 0; i < count.Length; i++)
{
while (count[i] != 0)
{
arr[index++] = i;
count[i]--;
}
}
}
以上代码完美运行。
但是,CLRS 中给出的算法是不同的。下面是我的实现
public int[] counting_sort(int[] arr)
{
int k = 100;
int[] count = new int[k + 1];
for (int i = 0; i < arr.Length; i++)
count[arr[i]]++;
for (int i = 1; i <= k; i++)
count[i] = count[i] + count[i - 1];
int[] b = new int[arr.Length];
for (int i = arr.Length - 1; i >= 0; i--)
{
b[count[arr[i]]] = arr[i];
count[arr[i]]--;
}
return b;
}
我已直接将其从伪代码翻译成 C#。代码不起作用,我得到一个 IndexOutOfRange 异常。
所以我的问题是:
- 第二段代码有什么问题?
- 在我的幼稚实现与书中给出的实现之间,算法方面的区别是什么?
【问题讨论】:
-
你用什么来输入
counting_sort的第二个版本?该算法有一些限制,允许输入值。 -
int[] arr包含 0-100 范围内的整数。我知道如果存在重复元素,该算法将不起作用。