首页 > 其他 > 详细

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

时间:2014-03-06 14:28:04      阅读:474      评论:0      收藏:0      [点我收藏+]
/*
实现一个排序算法,对某公司员工年龄进行排序,要求时间效率为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

公司员工年龄的排序,时间效率为O(n),布布扣,bubuko.com

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

原文:http://blog.csdn.net/walkerkalr/article/details/20545205

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!