时间复杂度为O(n)的排序算法
本随笔来源于《剑指offer》第二版
面试官:请实现一个排序算法,要求时间效率为O(n)。
应聘者:对什么数字进行排序,有多少个数字?
面试官:我们相对公司的所有员工的年龄排序。我们公司一共有几万名员工。
应聘者:也就是说数字的大小在一个较小的范围内,对吧?
面试官:嗯,是的。
应聘者:可以使用辅助空间吗?
面试官:只允许常量大小的辅助空间,不得超过O(n)。
#include<cstring>
#include<iostream>
using namespace std;
void SortAges(int ages[], int length)
{
if (ages == nullptr || length <= 0)
return;
const int oldestAge = 99;
int timesOfAge[oldestAge+1];
memset(timesOfAge, 0, oldestAge);
for (int i = 0; i < length; ++i)
{
int age = ages[i];
if (age <0 || age >oldestAge)
{
throw new 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;
}
}
}
posted on 2021-11-16 08:38 xcxfury001 阅读(171) 评论(0) 收藏 举报
浙公网安备 33010602011771号