对大量人的年龄排序

问题描述:

公司总共有几万名员工,对这些员工的年龄排序。要求只需用少量的辅助内存。

 

思路解析:

年龄总数在一个很小范围,例如0-100.这就可以用一个小数组存储了。逐个统计

年龄即可

 

参考代码:

void SortAge(int age[],int length)
{
    if (age == NULL || length == 0)
    {
        return;
    }

    const int oldestAge = 99;
    int TimeOfAges[oldestAge+1];

    for (int i = 0; i <= oldestAge;i++)
    {
        TimeOfAges[i] = 0;
    }
   
    //统计各年龄段的人数
    for (int i = 0;i < length;i++)
    {
        if (age[i] < 0 || age[i] > oldestAge)
        {
            throw new exception("age out of range");
        }
        ++TimeOfAges[age[i]];
    }

    //在原数组中根据统计到人数将数组重新排序
    //比如年龄最小的20岁有33个人,那么原数组前二十三个元素的值被置为20
    //以此类推这样整个数组就排序好了
    int index = 0;
    for (int i = 0;i <= oldestAge;i++)
    {
        for (int j = 0;j < TimeOfAges[i];j++)
        {
            age[index] = i;
            ++index;
        }
    }
}

posted @ 2014-11-29 16:34  阿木木在发呆  阅读(474)  评论(0编辑  收藏  举报