可以使用整数排序法, 内存太小无法堆排序.
#include <cstdio> #include <cstring> using namespace std; int main(){ unsigned int age[101]; int n,temp; while (scanf("%d", &n) == 1 && n){ memset(age, 0, sizeof(age)); for (int i = 0; i < n; i++){ scanf("%d", &temp); age[temp]++; } bool first = 1; for (int i = 1; i < 101; i++){ for (int j = 0; j < age[i];j++) { if (!first) printf(""); else first = false; printf("%d", i); } } printf(" "); } }优化输入输出也可以提高效率, 但是这个是最后考虑的优化要素.
函数名前 的inline 相当于c的宏定义, 降低大量函数引用消耗的时间.
使用cctype 中的 isdigit
#include <cstdio> #include <cstring> #include <cctype> using namespace std; inline int readint(){ char c = getchar(); while (!isdigit(c)) c = getchar(); unsigned int num = 0; while (isdigit(c)){ num = num * 10 + c - '0'; c = getchar(); } return num; } inline void writeint(unsigned int i){ char buf[10]; int p = 0; while (i){ buf[p++] = i % 10; i /= 10; } for (int j = p - 1; j >= 0; j++) putchar('0' + buf[j]); } int main(){ int n; int age[101]; while (n = readint()){ memset(age, 0, sizeof(age)); for (int i = 0; i < n; i++){ age[readint()]++; } bool first = true; for (int i = 1; i < 101; i++){ for (int j = 0; j < age[i]; j++){ if (!first) putchar(' '); else first = false; writeint(i); } } putchar(' '); } }