Detailed explanation of counting sorting

Preface: This article will give you a clear arrangement of counting sorting and explain the principle of counting sorting in detail.

Example: Now I have an array and I don’t know how many elements there are in it, but I want to sort it. How to sort it?

I'll just take an array first (pretend you don't know the number and elements in it)

int arr[5] = {1000,1001,1008,1007,1009}

Then we need to find the difference between the maximum value and the minimum value of the array, and then derive a closed interval, that is, the absolute value of the difference between each two numbers is within this range, which is [0, max-min]

Once you find the range, what do you do next?

Then widen this range into an integer array

1000 to 1009 are 10 elements

This array is all initialized to 0

That is int a[10]={0,0,0,0,0,0,0,0,0,0}

       Corresponding subscript 0 1 2 3 4 5 6 7 8 9

We find the difference value obtained by -min for each element. This difference value is the corresponding subscript of each array a. Every time a difference value is found, it corresponds to a[i]++

Then the array becomes int a[10]={1,1,0,0,0,0,0,1,1,1}

Then how do we sort the original array?

If the count is 0 in the a array, filter it out, that is, this number does not exist, and then until you find this number

So we can solve it with a loop

code show as below:

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
int main()
{
	int n = 0;
	//自行输入一个数代表数组的元素个数
	scanf("%d", &n);
	//VS不支持变长数组,所以我们把这个数组调大一些,以免越界
	int arr[100] = { 0 };
	for (int i = 0; i < n; i++)
	{
		scanf("%d", &arr[i]);
	}
	//输入完后开始找最大最小值了
	int max = arr[0];
	int min = arr[0];
	for (int i = 0; i < n; i++)
	{
		if (max < arr[i])
			max = arr[i];
		if (min > arr[i])
			min = arr[i];
	}
	int sub = max - min + 1;//求范围
	int* p = (int*)calloc(sizeof(int),sub);
	//判断一下
	if (p == NULL)
	{
		perror("calloc");
		return 1;
	}
	//计数
	for (int i = 0; i < n; i++)
	{
		p[arr[i] - min]++;
	}
	//计数完成后,再对原数组进行重新排序就行了
	int k = 0;//定义一个k变量对原数组进行输入数字
	int j = 0;
	for (j = 0; j < sub; j++)
	{
		while (p[j]--)
		{
			arr[k++] = j + min;
		}
	}
	for (int i = 0; i < n; i++)
	{
		printf("%d ", arr[i]);
	}
	free(p);
	p = NULL;
	return 0;
}

Guess you like

Origin blog.csdn.net/2301_79811170/article/details/134911871