问题:对一个公司的所有员工的年龄排序,公司总共有几万名员工,并且对每个年龄人数统计。实现的代码如下:
#include <iostream>
using namespace std;
//计算一个公司年龄的人口按从小到大顺序排列
void SortAges(int ages[], int length)
{
if (ages == NULL || length <= 0)
return;
const int oldestAge = 99;
int timesofAge[oldestAge + 1]; //用于存储每个年龄的人数
//对数组进行初始化
for (int i = 0; i <= oldestAge; i++)
{
timesofAge[i] = 0;
}
for (int i = 0; i < length; i++)
{
int age = ages[i];
//异常数据
if (age<0 || age>oldestAge)
cout << "参数有误" << endl;
//记录一个年龄的人数
++timesofAge[age];
}
//对各个年龄段进行排序
int index = 0;
for (int i = 0; i <= oldestAge; i++)
{
for (int j = 0; j < timesofAge[i]; ++j)
{
ages[index] = i; //以有序的方式重新存储
++index;
}
}
for (int i = 0; i < length; i++)
{
cout << ages[i] << endl;
}
}
int main()
{
int *p = new int[15]{1, 2, 3, 6, 3, 6, 36, 4, 5, 3, 7, 2, 90, 34, 45};
SortAges(p, 15); //测试函数
return 0;
}
输出的结果如下: