目录
前言
优点:时间复杂度O(n);
缺点:需要额外的空间来存储计数数组,它的空间复杂度也是O(n)。
适用于:数据范围不是很大
一.计数排序概念
计数排序是一种稳定的线性时间复杂度排序算法,适用于一定范围内的整数排序。
这种排序算法的核心思想是将输入的数据值转化为键,存储在额外开辟的数组空间中。它通过以下步骤进行排序:
- 确定计数数组大小:根据待排序数组中的最大值和最小值确定计数数组的大小(即数值范围k)。
- 统计元素出现次数:遍历待排序数组,对每个元素的出现次数进行统计,并将结果存储在计数数组中。
- 修改计数数组:从计数数组的第一个元素开始,将每个元素的值更新为其索引值与前一个元素的值之和,这样每个索引位置上的值就代表了小于等于当前索引值的元素个数。
- 构建输出数组:再次遍历待排序数组,使用计数数组中的信息将每个元素放置在其在输出数组中的适当位置上。
需要注意的是,计数排序的时间复杂度是O(n+k),其中n是待排序数组的长度,k是数值范围。由于需要额外的空间来存储计数数组,它的空间复杂度也是O(n+k)。因此,当数据范围不是很大时,计数排序是一个非常高效的排序方法。
二.计数排序思路
创建一个数组countA;用于统计原数组中数字出现的次数;再通过次数进行排序;
2.1寻找最值(max,min)
找到原数组中最大的与最小的数;再寻找范围:max-min+1=range(范围);
原数组为a[n],假设数组中最小值为2000,最大值为5000;那么需要开辟的空间为(5000-2000=3000);
int max = a[0], min = a[0];
for (int i = 1; i < n; ++i)
{
if (a[i] > max)
{
max = a[i];
}
if (a[i] < min)
{
min = a[i];
}
}
int range = max - min + 1;
2.2相对映射
这里是相对映射关系,不是绝对映射;下图a[0]=2000;映射的位置于a[0]-2000=0的位置,
再使用count[]进行统计次数
2.3统计次数
巧妙利用count[]把区间内每个数字的出现次数进行累加
注意:
count[a[i]-min]++(相当于找到这个数字,对它进行记录++)
countA[]数组:(记录每个数组出现的次数)
a[i]:(原数组位于下标i的数字)
a[i]-min:(相对映射,也就是把countA[]数组下标)(countA数组不存放元素,只存放次数)
countA[a[i]-min]:(需要累加的数字位置)
countA[a[i]-min]++:(重复数字累加)
// 统计次数
int* countA = (int*)malloc(sizeof(int) * range);
if (countA == NULL)
{
perror("malloc fail");
return;
}
memset(countA, 0, sizeof(int) * range);
for (int i = 0; i < n; ++i)
{
countA[a[i] - min]++;
}
2.4排序
这里比较抽象,用统计次数的数组count[],通过次数进行逐个排序
// 排序
int j = 0;
for (int i = 0; i < range; ++i)
{
while (countA[i]--)
{
a[j] = i + min;
++j;
}
}
free(countA);
三.计数排序全部代码
3.1全部代码
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
void PrintArry(int* a, int n)
{
for (int i = 0; i < n; ++i)
{
printf("%d ", a[i]);
}
printf("\n");
}
// 时间复杂度:O(N+range)
// 空间复杂度:O(range)
// 适合数据范围集中,也就是range小
// 只适合整数,不适合浮点数、字符串等
void CountSort(int* a, int n)
{
int max = a[0], min = a[0];
for (int i = 1; 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);
if (countA == NULL)
{
perror("malloc fail");
return;
}
memset(countA, 0, sizeof(int) * range);
for (int i = 0; i < n; ++i)
{
countA[a[i] - min]++;
}
// 排序
int j = 0;
for (int i = 0; i < range; ++i)
{
while (countA[i]--)
{
a[j] = i + min;
++j;
}
}
free(countA);
}
void TestCountSort()
{
int a[] = { 5,6,7,8,3,4,5,6,7,8,4,5,6,7,8,9,5,6,7,5,4,5,5,5,5 };
PrintArry(a, sizeof(a) / sizeof(a[0]));
CountSort(a, sizeof(a) / sizeof(a[0]));
PrintArry(a, sizeof(a) / sizeof(a[0]));
}
int main()
{
TestCountSort();
return 0;
}
3.2运行结果
以上就是本期补齐的内容,欢迎参考指正,如有不懂,欢迎评论或私信出下期!!!