您的位置:首页 > 其它

实现一个算法,对公司员工年龄进行排序,时间效率要求O(n)

2017-03-04 15:35 736 查看
//实现一个算法,对公司员工年龄进行排序,时间效率要求O(n)
#include<iostream>
void sortAges(int ages[], int length)
{
if (ages == NULL || length < 0)
{
return ;
}

//因为年龄是一个小范围的内,我们可以使用辅助内存

const int oldestAge = 99;
int timesOfAge[oldestAge + 1] = {0};

for (int i = 0; i < length; ++i)
{
int age = ages[i];

if (age<0 || age>oldestAge)
{
throw new std::exception("age out_of range.");
}
++timesOfAge[age];

}

int index = 0;
for (int i = 0; i <= oldestAge; ++i)
{
for (int j = 0; j < timesOfAge[i]; ++j)
{
ages[index] = i;
++index;
}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐