题目描述:对一个公司的所有员工(可能上万)的年龄排序,只允许使用常量大小的辅助空间。
解题思路:采用长度100的整数数组作为辅助空间,对0-99岁出现的次数进行计数。某个年龄出现多少次,就在原数组依次(下标)按顺序重新赋值排列。
测试用例:
//测试用例
int main(){
//随机创建一个年龄数组(0-99岁)
int ages[20000];
for(int i = 0; i < 20000; ++i)
ages[i] = rand() % 100; //随机得到年龄99
//按从小到大对年龄数组排序
sortAges(ages, 20000);
//输出排序后的结果
for(int i = 0; i < 20000; ++i)
std::cout << ages[i] << " ";
return 0;
}
sortAges函数实现:
void sortAges(int ages[], int length){
if(ages == NULL || length <= 0)
return;
//需要一个保存年龄0-99的数组,下标即年龄,出现次数全部赋值为0次
int timesOfArges[100];
for(auto i = 0; i < 100; ++i)
timesOfArges[i] = 0;
//最大年龄为99
const int oldestAge = 99;
//遍历全部年龄
for(auto i = 0; i < length; ++i){
//依次取出年龄
int age = ages[i];
//如果不在合法年龄之间(0-99)
if(age < 0 || age > oldestAge)
throw new std::exception("Age out of range.");
++timesOfArges[age]; //否则,对年龄(即下标)次数进行计数
}
int index = 0; //新的下标
//在辅助空间数组计数完毕后,遍历辅助空间数组,依次对原数组按顺序赋值
for(auto i = 0; i <= oldestAge; ++i){
for(auto j = 0; j < timesOfArges[i]; ++j){ //j为某个年龄出现的次数
ages[index] = i;
++index;
}
}
}