码迷,mamicode.com
首页 > 其他好文 > 详细

剑指offer 例题

时间:2015-06-26 12:56:06      阅读:100      评论:0      收藏:0      [点我收藏+]

标签:

题目:
实现一个排序算法,排序对象是本公司员工的年龄,要求时间复杂度O(n),空间复杂度不能超过O(n)。

#include<iostream>
using namespace std;
void SortAge(int Ages[],int length)
{
    if (NULL == Ages || length <= 0)
        return;
    const int oldAge = 99;
    int timesOfAge[oldAge+1];
    for (int i = 0; i <= oldAge; i++)
        timesOfAge[i] = 0;
    for (int j = 0; j < length;j++)
    {
        int age = Ages[j];
        if (age>oldAge || age < 0)
            throw exception("Invalid Value!");
        timesOfAge[age]++;
    }
    int index = 0;
    for (int k = 0; k <= oldAge; k++)
    {
        for (int s = 0; s < timesOfAge[k]; s++)
        {
            Ages[index] = k;
            index++;
        }
    }


}

int main()
{
    int Age[] = { 1, 5, 45, 56, 8, 6, 78, 5, 2, 4, 6, 23, 66, 65, 26, 23 };
    SortAge(Age,16);
    for (size_t i = 0; i < 16; i++)
    {
        cout << Age[i] << " ";
    }

    return 0;
}

剑指offer 例题

标签:

原文地址:http://blog.csdn.net/u011058765/article/details/46648529

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!