【发布时间】:2017-03-21 11:11:05
【问题描述】:
对于x > 0,我有一个计数排序,它按降序对我的数组进行排序。然而,当考虑负数时,我的实现逻辑崩溃了,因为我在辅助数组values 中使用负索引。我正在考虑以某种方式使用 uint 但我不是很熟悉。
我怎样才能克服这个使用计数排序。
static void countingSort(int[] arr)
{
int i, j, max = -1; // I think it falls apart about here
int[] values;
for (i = 0; i < arr.Length; i++)
if (arr[i] > max) max = arr[i];
values = new int[max + 1];
//Here it reaches for a negative index when i = 2,looking for -6.
for (i = 0; i < arr.Max(); i++)
values[arr[i]]++;
i = 0; j = values.Length - 1;
while (i < arr.Length)
{
if (values[j] > 0)
{
values[j]--;
arr[i] = j;
i++;
}
else j--;
}
}
我知道我的问题在于帮助数组的索引。而且由于我不想继续制作带有负索引的数组,所以我有点难过。
如果不将整个类实现为索引器,您甚至可以在 c# 中做到这一点吗? 我知道你可以在 C 中做到这一点,它的定义很明确:
来自 C99 §6.5.2.1/2: 下标运算符[]的定义是E1[E2]等同于(*((E1)+(E2)))。
我的测试数组是{ 8, 5, -6, 7, 1, 4 }
我的预期输出是{ 8, 7, 5, 4, 1, -6 }
【问题讨论】:
-
好吧,C# 不像 C 那样在其索引器中执行“指针数学”,所以不,它们不等价。
标签: c# sorting counting-sort