公司员工年龄的排序,时间效率为O(n)

/*
实现一个排序算法,对某公司员工年龄进行排序,要求时间效率为O(n)。
可以使用辅助空间。只允许使用常量大小辅助空间,不得超过O(n)。
*/
#include <iostream>
using namespace std;

void ageSort(int* arr, int length)
{
	if(arr == NULL || length <=0 )
		return;

	const int oldestAge = 99;
	int timeOfAge[oldestAge+1];	//存放每个年龄的出现次数
	for(int i=0; i<=oldestAge; i++)	//将每个年龄出现的次数清0
	{
		timeOfAge[i] = 0;
	}
	for(int i=0; i<length; i++)	//计算每个年龄出现的次数
	{
		int age = arr[i];
		if(age<0 || age>oldestAge)
			throw new std::exception("age out of range.");
		++timeOfAge[i];
	}
	int index = 0;
	for(int i=0; i<=oldestAge; ++i)	//根据每个年龄出现的次数,给arr数组赋值,
	{								//此时已经是排序好的数列
		for(int j=0; j<timeOfAge[i]; ++j)
		{
			arr[index] = i;
			++index;
		}
	}
}
void test()
{
	int arr[10]={1,2,3,4,34,4,5,15,9,10};
	ageSort(arr,10);
	for(int i=0; i<10;i++)
		cout<<arr[i]<<'\t';
}
int main()
{
	test();
	return 0;
}


 

==参考剑指offer
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值