天天看點

排序算法--對公司員工年齡的排序

/*
.................................//排序算法--對公司員工的年齡排序,要求時間效率O(n)
解題思路:
   公司員工的年齡有一個範圍 這裡規定0~99
   用長度100的整數數組作為輔助空間換來了O(n)的時間效率。
*/
#include<stdio.h>
#define N 10
void SortAges(int ages[],int length)
{
int i ;
if(ages == NULL ||length <= )
return ;
const int oldAge = ; //年齡的允許範圍是0~99
int timeOfAge[oldAge+];
for(i = ;i<=oldAge;i++)  //将數組timeOfAge[0]~timeOfAge[99]初始化為0
timeOfAge[i] = ;
for(i = ;i<length;++i)
{
int age = ages[i]; //員工年齡
if(age < ||age > oldAge)
printf("age out of range\n");
++timeOfAge[age];//  其年齡下标對應的數組位置大小加1 ,即用來統計每個年齡出現的次數
}
int index = ;
for(i = ;i <= oldAge;i++)
{
int j ;
for(j = ;j<timeOfAge[i];++j)
{
ages[index] = i; //某個年齡出現了多少次,就在數組ages裡設定幾次該年齡
++index;
}
}
}
int main()
{
int age[N];
int i;
printf("請輸入員工的年齡:\n");
for(i = ;i<N;i++)
{
scanf("%d",&age[i]);
}
SortAges(age,N);
printf("排序後員工的年齡:\n");
for(i = ;i<N;i++)
printf("%d ",age[i]);
return ;
}
#endif
           

繼續閱讀