排序- 计数排序

#include 
#include 

const int N = 1e5 + 10;

int n, k;
int a[N], b[N], c[N];

int max(int a, int b)
{
	return a > b ? a : b;
}

void counting_sort(int a[], int b[], int k)
{
	int c[k + 1] = {0};
	
	for (int i = 0; i < n; ++ i) c[a[i]] ++;
	for (int i = 1; i <= k; ++ i) c[i] += c[i - 1];
	for (int i = n - 1; i >= 0; -- i)
	{
		b[c[a[i]]] = a[i];
		c[a[i]] --;
	}
	return ;
}

int main()
{
	scanf("%d", &n);
	for (int i = 0; i < n; ++ i) 
	{
		scanf("%d", &a[i]);
		k = max(k, a[i]);
	}
	
	counting_sort(a, b, k);
	
	for (int i = 1; i <= n; ++ i) printf("%d ", b[i]);
	
	return 0;
} 

/*
10
95 94 91 98 99 90 99 93 91 92

90 91 91 92 93 94 95 98 99 99
*/

你可能感兴趣的:(排序,c++,算法)