计数排序(Count Sort)是一个非基于比较的排序算法,该算法于1954年由 Harold H. Seward 提出。它的优势在于在对一定范围内的整数排序时,它的复杂度为Ο(n+k)(其中k是整数的范围),快于任何比较排序算法。
计数排序的思想是在给定的一组序列中,先找出该序列中的最大值和最小值,从而确定需要开辟多大的辅助空间,每一个数在对应的辅助空间中都有唯一的下标。
- 找出序列中最大值和最小值,开辟Max-Min+1的辅助空间
- 最小的数对应下标为0的位置,遇到一个数就给对应下标处的值+1,。
- 遍历一遍辅助空间,就可以得到有序的一组序列
#include <iostream>
using namespace std;
void countSort(int data[], int len)
{
//find the min, max value of the array data
int min = data[0];
int max = min;
for(int i = 1; i < len; i++)
{
if(data[i] < min )
min = data[i];
if(data[i] > max)
max = data[i];
}
//Initialize the temp array
int* temp = new int[max-min+1];
for(int i = 0; i < max-min+1; i++)
temp[i] = 0;
//Count the time that appears in the array, then mark it in the temp array
for(int i = 0; i < len; i++)
temp[data[i] - min]++;
//Go through the temp array, assign the value back to target array accroding to each data appear time.
int j = 0;
for(int i = 0; i < max-min+1; i++)
{
while((temp[i]--) > 0)
data[j++] = min + i;
}
delete[] temp;
}
int main() {
int arr[10] = {1,5,4,3,7,6,9,10,8,2};
countSort(arr, 10);
for(int i = 0; i < 10; i++)
cout << arr[i] << endl;
return 0;
}