1、测试代码
#include <iostream>
using namespace std;
int g_loop = 0; /* 循环计数 */
int g_move = 0; /* 数据移动次数 */
void output_info(int *buff,int len, int flag)
{
int i;
if(0 == flag)
{
cout << "before: ";
}
else
{
cout << "after: ";
}
for(i = 0; i < len; ++i)
{
cout << *(buff + i) << " ";
}
cout << endl;
}
void count_sort(int arr[], int len)
{
int max;
int min;
int i;
int *temp;
int pos = 0;
max = min = arr[0];
for(i = 1; i < len; ++i)
{
if(arr[i] > max)
{
max = arr[i];
}
if(arr[i] < min)
{
min = arr[i];
}
}
/* 建立计数数组,并初始化 */
temp = new int[max - min + 1]();
cout << "min=" << min << endl;
cout << "max=" << max << endl;
/* 计数 */
for(i = 0; i < len; ++i)
{
++g_loop;
++temp[arr[i] - min];
}
/* 打印计数值 */
for(i = min; i <= max; ++i)
{
cout << "temp[" << i << "]=" << temp[i - min] << endl;
}
cout << endl;
#if 1
/* 数据回填 */
output_info(arr, len, 0);
for(i = min; i <= max; ++i)
{
while(temp[i - min])
{
arr[pos++] = i;
--temp[i - min];
++g_move;
}
}
output_info(arr, len, 1);
#else
// ps: 优化,能区分相同的数位置
int sum = 0;
cout << "change:" << endl;
output_info(temp, len + 1, 0);
for(i = min; i <= max; ++i)
{
sum += temp[i - min];
temp[i - min] = sum;
}
output_info(temp, len + 1, 1);
int *sortArray = new int[len];
for (i = len - 1; i >= 0; --i)
{
sortArray[temp[arr[i] - min] - 1] = arr[i];
--temp[arr[i] - min];
}
output_info(sortArray, len, 1);
delete[] sortArray;
#endif
delete[] temp;
}
int main()
{
int array[10]= {20,19,18,17,15,15,14,13,10,10};
int len = sizeof(array) / sizeof(array[0]);
count_sort(array, len);
cout << endl;
cout << "move=" << g_move << endl;
cout << "loop=" << g_loop << endl;
return 0;
}
2、测试log
min=10
max=20
temp[10]=2
temp[11]=0
temp[12]=0
temp[13]=1
temp[14]=1
temp[15]=2
temp[16]=0
temp[17]=1
temp[18]=1
temp[19]=1
temp[20]=1
before: 20 19 18 17 15 15 14 13 10 10
after: 10 10 13 14 15 15 17 18 19 20
move=10
loop=10
3、算法分析
- 非原地排序算法;
- 稳定排序算法;
- 空间复杂度 O(k);
- 时间复杂度 O(n + k)。
k表示临时数组的大小,当k不是很大并且序列比较集中时,计数排序很快。该算法只能排整数。