zcmu-1030 age sort(数组下标排序法)

Description

You are given the ages (in years) of allpeople of a country with at least 1 year of age. You know that no individual in that country lives for 100 or more years. Now, you are given a very simple task of sorting all the ages in ascending order.

Input

There are multiple test cases in the input file. Each case starts with an integer (0<n<=1000000), the total number of people. In the next line, there are integers indicating the ages. Input is terminated with a case where = 0. This case should not be processed.

Output

For each case, print a line with space separated integers. These integers are the ages of that country sorted in ascending order.

Sample Input

5 3 4 2 1 5 5 2 3 2 3 1 0

Sample Output

1 2 3 4 5 1 2 2 3 3

试了无数次...这么水的一道题,搞了很久。

思路:

 具体解释写在注释里面很清楚了,如果用数组记录每个人的年龄的话就太浪费空间了呐,因为年龄只有1-100,所以从这一方面考虑,用数组下标记录年龄,用数组记录不同年龄的人数更划算!

#include<stdio.h>
int main()
{
    int i,n,t;
    while(~scanf("%d",&n)){
        int a[101]={0},t=1;
        if(n==0)
            break;
        while(n--){
            scanf("%d",&i);//这里用数组的下标记录年龄
            a[i]++;//数组实际的值就是该年龄的人数
        }
        for(i=1;i<101;i++)//年龄从小到大输出
            while(a[i]-->0){//如果存在这个年龄段的人的话就输出他的年龄,这里注意a[i]每次循环都-1了哟
                if(t){
                    printf("%d",i);
                    t=0;//第一个数前面不用输出空格
                }
                else
                    printf(" %d",i);
            }
        printf("\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/hzyhfxt/article/details/81430932
今日推荐