思路:借助一个长度为100的数组,因为设年龄最大为99,所以年龄范围为0-99。然后先将数组全部初始化为0,然后用这个数组统计年龄的次数,比如说年龄为[4,5,2,1,2],然后在数组下标1就会得到1,数组下标2会得到2,下标4和5也得到1,其他均为0。统计完年龄数组后,就要去遍历这个统计的数组,将不小于0的下标依次重新赋值到年龄数组,然后就会形成有序年龄数组。
辅助空间:长度为100的数组; 时间复杂度:O(n)
#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) //将数组元素全部设为0
{
timesOfAge[i] = 0;
}
for (int i = 0; i < length; ++i)
{
int age = ages[i];
if (age < 0 || age > oldestAge)
{
cout << "age out of range." << endl;
return;
}
++timesOfAge[age];
}
int index = 0;
for (int i = 0; i <= oldestAge; ++i)
{
for (int j = 0; j < timesOfAge[i]; ++j)
{
ages[index] = i;
++index;
}
}
}
int main()
{
int a[7] = {4, 5, 4, 2, 5, 1,3};
SortAges(a, 7);
for (int i = 0; i < 7; i++)
{
cout << a[i] <<" ";
}
return 0;
}