📅  最后修改于: 2020-10-15 01:22:55             🧑  作者: Mango
这是一种基于键的排序技术,即根据小整数的键来收集对象。计数排序计算对象的出现次数并存储其键值。通过添加先前的关键元素并分配给对象来形成新的数组。
时间复杂度:O(n + k)是最坏的情况,其中n是元素数,k是输入范围。
空间复杂度:O(k)k是输入范围。
Complexity | Best Case | Average Case | Worst Case |
---|---|---|---|
Time Complexity | Ω(n+k) | θ(n+k) | O(n+k) |
Space Complexity | O(k) |
程序
#include
void counting_sort(int A[], int k, int n)
{
int i, j;
int B[15], C[100];
for (i = 0; i <= k; i++)
C[i] = 0;
for (j = 1; j <= n; j++)
C[A[j]] = C[A[j]] + 1;
for (i = 1; i <= k; i++)
C[i] = C[i] + C[i-1];
for (j = n; j >= 1; j--)
{
B[C[A[j]]] = A[j];
C[A[j]] = C[A[j]] - 1;
}
printf("The Sorted array is : ");
for (i = 1; i <= n; i++)
printf("%d ", B[i]);
}
/* End of counting_sort() */
/* The main() begins */
int main()
{
int n, k = 0, A[15], i;
printf("Enter the number of input : ");
scanf("%d", &n);
printf("\nEnter the elements to be sorted :\n");
for (i = 1; i <= n; i++)
{
scanf("%d", &A[i]);
if (A[i] > k) {
k = A[i];
}
}
counting_sort(A, k, n);
printf("\n");
return 0;
}