Bucket sort 桶排序(含EOF)

Description:
Input a couple of numbers (0~100) and end of EOF.

If number > 20, it shuold be mapped to [0, 20],whitch is mean ‘number %= 21’

Output all these numbers by ascending oder.

Output format: behind every number, there is a space ’ ‘. And no ‘\n’

For example:

[Input]

1 2 22 3 3 44 5 55 6 66 7 20 21 23 100 101

[Output]

0 1 1 2 2 2 3 3 3 5 6 7 13 16 17 20

Hint:
輸入數據範圍較集中,建議用桶排序。

windows下出入EOF:換到新的一行,輸入ctrl+Z

linux下輸入EOF:換到新的一行,輸入ctrl+D
代碼塊
使用冒泡排序

#include<stdio.h>
int main() {
    int a[100], b, t;
    int i = 0, k, j;
    while ((scanf("%d", &b))!= EOF) {
        a[i] = b;
        if (a[i] > 20) {
            a[i] = a[i] % 21;
        }
        i++;
    }
    // 注意冒泡排序寫法
    for (k = 0; k < i; k++)
        for (j = 0; j < i - 1; j++)
        // 注意此處應該寫i—1
        if (a[j] > a[j + 1]) {
            t = a[j];
            a[j] = a[j + 1];
            a[j + 1] = t;
        }
    for (k = 0; k < i; k++)
    printf("%d ", a[k]);
return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章