时间复杂度为O(n)的排序算法

本随笔来源于《剑指offer》第二版

 

面试官:请实现一个排序算法,要求时间效率为O(n)。

应聘者:对什么数字进行排序,有多少个数字?

面试官:我们相对公司的所有员工的年龄排序。我们公司一共有几万名员工。

应聘者:也就是说数字的大小在一个较小的范围内,对吧?

面试官:嗯,是的。

应聘者:可以使用辅助空间吗?

面试官:只允许常量大小的辅助空间,不得超过O(n)。

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#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   xcxfury001  阅读(160)  评论(0编辑  收藏  举报

编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· Ollama——大语言模型本地部署的极速利器
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· Windows编程----内核对象竟然如此简单?
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示