# 对公司几万名员工按年龄排序（时间复杂度为O(N)）

【1】题目
【2】分析
【3】测试代码
【4】测试结果

### 【3】测试实现：

#include<iostream>
using namespace std;
//=====================================算法==========================================
int sortage(int ages[], int length)
{
if(ages == NULL || length <= 0)
{
printf("参数传递错误：ages == NULL || length <= 0\n");
return -1;
}

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 )
{
printf("年纪不在有效范围内\n");
return -1;
}

++timesofage[age];
}

int index = 0;
for(int i = 0; i< oldestage ;++i )
{
for(int j = 0; j<timesofage[i]; ++j )
{
ages[index] = i;
++index;
}
}
return 0;
}
//==================================测试代码=====================================
void test()
{
int arr[20]={20,30,44,32,22,34,66,77,55,44,31,22,44,32,44,65,24,22,20, 35};
int length = sizeof(arr)/sizeof(arr[0]);
printf("共有%d位员工年纪待排序\n",length );
int ret = sortage(arr,length);
if(ret == 0)
{
printf("排序后：");
for(int i = 0;i<length ; ++i )
{
printf("%d ",arr[i]);
}
printf("\n");
}
}

int main()
{
test();
return 0;
}

### 【4】测试结果如下：

1、ages[20] = {20,30,44,32,22,34,66,77,55,44,31,22,44,32,44,65,24,22,20, 35}

2、ages[20] = {100,30,44,32,22,34,66,77,55,44,31,22,44,32,44,65,24,22,20, 35}

3、int ret = sortage( NULL , length);

3、int ret = sortage( arr , 0);