我听说过计数排序,并根据自己的理解编写了自己的版本。
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
中使用了什么输入?该算法有一些限制,只允许特定的输入值。 - Jacobint[] arr
包含范围在0-100之间的整数。我知道如果存在重复元素,该算法将无法工作。 - rohit89