[Counting sort] The principle and implementation of counting sort (C language implementation)


1. Sorting principle

insert image description here

Relative mapping:
insert image description here

2. Counting and sorting code

void CountSort(int* a, int n) {
    
    
	int max = a[0];
	int min = a[0];
	for (int i = 1; i < n; i++) {
    
    
		if (min > a[i]) {
    
    
			min = a[i];
		}
		if (max < a[i]) {
    
    
			max = a[i];
		}
	}
	//首先找出最大与最小的元素
	int range = max - min + 1;
	//确定最大与最小之间的距离
	int* count = (int*)calloc(range, sizeof(int));
	if (count == NULL) {
    
    
		perror("calloc");
		return;
	}
	//创建一个专门用来存储数组中元素出现次数的数组
	//并且初始化数组里元素为0
	for (int i = 0; i < n; i++) {
    
    
		count[a[i] - min]++;
		//我们最小值就为min
		//例如:
		//min=100,a【0】=102
		//然后count【2】的位置会加一,记录102的出现次数
		//然后我们min+count对应的元素下标2就为102
		//这样我们就可以获得count记录的是哪一个数出现的次数
	}
	int j = 0;
	for (int i = 0; i < n; i++) {
    
    
		while (count[i]--) {
    
    
			//从count【0】开始
			//一次把count记录次数还原为该数据为min+i
			//若count【i】不为0继续进行循环
			a[j++] = min + i;
		}
	}

	free(count);

}

Summarize

Usage: It can be used when the data is relatively concentrated and all are integers, and it
is not suitable for sorting with scattered ranges or non-integers.
Time complexity: O(n+range)

Guess you like

Origin blog.csdn.net/m0_74774759/article/details/131012953