/*
实现一个排序算法,对某公司员工年龄进行排序,要求时间效率为O(n)。
可以使用辅助空间。只允许使用常量大小辅助空间,不得超过O(n)。
*/
#include <iostream>
using namespace std;
void ageSort(int* arr, int length)
{
if(arr == NULL || length <=0 )
return;
const int oldestAge = 99;
int timeOfAge[oldestAge+1]; //存放每个年龄的出现次数
for(int i=0; i<=oldestAge; i++) //将每个年龄出现的次数清0
{
timeOfAge[i] = 0;
}
for(int i=0; i<length; i++) //计算每个年龄出现的次数
{
int age = arr[i];
if(age<0 || age>oldestAge)
throw new std::exception("age out of range.");
++timeOfAge[i];
}
int index = 0;
for(int i=0; i<=oldestAge; ++i) //根据每个年龄出现的次数,给arr数组赋值,
{ //此时已经是排序好的数列
for(int j=0; j<timeOfAge[i]; ++j)
{
arr[index] = i;
++index;
}
}
}
void test()
{
int arr[10]={1,2,3,4,34,4,5,15,9,10};
ageSort(arr,10);
for(int i=0; i<10;i++)
cout<<arr[i]<<'\t';
}
int main()
{
test();
return 0;
}
公司员工年龄的排序,时间效率为O(n)
最新推荐文章于 2020-10-26 10:41:46 发布