数据结构:计数排序

void CountSort(int* a, int n)
{
	int max = a[0];
	int min = a[0];

	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);

	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]--) != 0)
		{
			a[j++] = i + min;
		}

	}

}

你可能感兴趣的:(数据结构,c语言,学习,数据结构,排序算法)