题目:
对所有员工年龄排序,可以使用辅助空间,但不得超过O(n)
算法:
数字的大小在一个比较小的范围内,可以使用数组计数法排序。
公司员工的年龄是用一个范围,数组timesOfAge用来统计每个年龄出现的次数。从小到大遍历年龄,更新排序后的ages数组,到某个年龄时到timesofage数组里找此年龄出现的次数,顺序写到ages后,相当于从小到大排序。
void SortAges(int ages[],int length){
//ages 里保存未排序的员工年龄,length为员工数
if(ages == NULL || length <= 0)
return ;
//设定年龄最大值为99,限定在0~99之间
const int oldestage = 99;
//初始化年龄次数记录数组,数组内保存年龄对应出现的次数
int timesOfAges[oldestage+1];
for (int i = 0; i < oldestage; i++)
{
timesOfAges[i] = 0;
}
//统计次数
for (int j = 0; j < length; j++)
{
if(ages[j] <0 || ages[j] > 99)
return ;
int age = ages[j];
timesOfAges[age] += 1;
}
//index记录更新后的ages数组下标
int index = 0;
//i 记录年龄递增
for (int i = 0; i <= oldestage; i++)
{
//j记录timesofages数组内同一个年龄出现的次数,同时放入ages数组内更新
for (int j = 0; j < timesOfAges[i]; j++)
{
ages[index++] = i;
}
}
}