9 Count sort

Count sorting is a sorting algorithm similar to bucket sorting. Its advantage is to sort an array of a known number range. It creates an array C with a length of this data range, and each element in C records the number of occurrences of the corresponding record in the array to be sorted. Non-situ sorting.

 

(1) Ideas:

The basic idea of ​​the counting sorting algorithm is to determine the number of elements in the sequence whose value is less than x for each element x in a given input sequence. Once you have this information, you can store x directly in the correct position in the final output sequence. For example, if the value of only 17 elements in the input sequence is less than the value of x, then x can be directly stored in the 18th position of the output sequence.

 

(2) Complexity analysis:

(2.1) Time complexity:   

         Average situation: O(n).

(2.2) Space complexity:

         O (n)。

 

(3) Stability:

         The counting sort is stable. Pay attention to the bucket from back to front.

 

code segment:

#include <stdio.h>
#define SIZE 8

void count_sort(int* A,int* B,int len,int k);

int main()
{
    int A[SIZE]={2,5,3,0,2,3,0,3},B[SIZE];
    count_sort(A, B, SIZE, 5);		//5:数组元素最大值
    return 0;
}

void count_sort(int* A,int* B,int len,int k)
{
	const int C_len=9;		//k+1
	int C[C_len];
	int i,value,pos;
	for(i=0;i<=k;i++)		//置0
	{
		C[i]=0;
	}
	for(i=0;i<len;i++)		//统计各个桶中元素的个数
	{
		C[A[i]]++;
	}
	for(i=1;i<=k;i++)		//count[i]表示桶的右边界索引	
	{
		C[i]=C[i]+C[i-1];	
	}
	for(i=len-1;i>=0;i--)	//把数据依次装入桶B[],从后向前入桶保证计数排序稳定性
	{
		value=A[i];
		pos=C[value];
		B[pos-1]=value;
		C[value]--;
	}
}

 

Guess you like

Origin blog.csdn.net/u012906122/article/details/103606042