剑指offer 例题

题目:
实现一个排序算法,排序对象是本公司员工的年龄。要求时间复杂度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;
}
posted @ 2015-12-18 14:33  phlsheji  阅读(138)  评论(0编辑  收藏  举报