void CountSort(int* a, int n)
{
int max = a[0];
int min = a[0];
//for循环找到原数组中的最大值和最小值
for (int i = 0; i < n; i++)
{
if (a[i]>max)
{
max = a[i];
}
if (a[i] < min)
{
min = a[i];
}
}
int range = max - min + 1;
int* counta = (int*)malloc(sizeof(int)*range);
memset(counta, 0, sizeof(int)*range);//将数组counta初始化为0
//遍历原数组,统计每个数出现的次数
for (int i = 0; i < n; i++)
{
counta[a[i] - min]++;
}
int index = 0;
//遍历范围,对原数组排序
for (int i = 0; i < range; i++)
{
while (counta[i]--)
{
a[index] = i + min;
index++;
}
}
}
计数排序
最新推荐文章于 2020-02-23 12:03:06 发布