#include <stdio.h> #include <stdlib.h> int main() { int a[] = {4,5,4,1,4,90,5,50,70,1,20,50,65536,0,-3,-1,-4,-2,-6552,999}; int max = 0, min = 0, i = 0,n = 0, *b = NULL, *c = NULL; for (i=0, n=sizeof(a)/sizeof(int); i<n; i++) if(a[i] >= max) max = a[i]+1; for (i=0, n=sizeof(a)/sizeof(int); i<n; i++) if(a[i] < 0 && a[i] < min) min = a[i]; if ((b = (int *) calloc(max , sizeof(int))) == NULL) return 1; if (-min) if ((c = (int *) calloc(-min , sizeof(int))) == NULL) return 1; for (i=0, n=sizeof(a)/sizeof(int); i<n; i++) if(a[i]>=0) b[a[i]]++; else c[-a[i]]++; for (i=-min; i>0; i--) while (c[i]-- > 0) printf("%d\n",-i); for (i=0, n=max; i<n; i++) while (b[i]-- > 0) printf("%d\n",i); free(b); free(c); // release pointer b = NULL; c = NULL; // no wild pointer return 0; }
运行:gcc c.c; ./a.out
输出:
-6552
-4
-3
-2
-1
0
1
1
4
4
4
5
5
20
50
50
70
90
999
65536
===========================华丽的分割线====================================
于 2012年2月20日更新:
#include <stdio.h> #include <stdlib.h> int *linear_sort(int *a, int n) { int max = 0, min = 0, i = 0, j = 0, *b = NULL, *c = NULL, *r = NULL; for (i=0; i<n; i++) { if(a[i] >= max) max = a[i]+1; if(a[i] < 0 && a[i] < min) min = a[i]; } if ((b = (int *) calloc(max , sizeof(int))) == NULL) exit(1); if (-min) if ((c = (int *) calloc(-min , sizeof(int))) == NULL) exit(1); if ((r = (int *) calloc(n , sizeof(int))) == NULL) exit(1); for (i=0; i<n; i++) if(a[i]>=0) b[a[i]]++; else c[-a[i]]++; for (i=-min; i>0; i--) while (c[i]-- > 0) r[j++] = -i; for (i=0, n=max; i<n; i++) while (b[i]-- > 0) r[j++] = i; free(b); free(c); // release pointer b = NULL; c = NULL; // no wild pointer return r; } int main() { int a[] = {4,5,4,1,4,90,5,50,70,1,20,50,65536,0,-3,-1,-4,-2,-6552,999}; int i = 0, n = sizeof(a)/sizeof(int); int *b = linear_sort(a, n); for (i=0; i<n; i++) { printf("%d\n",b[i]); } free(b); b = NULL; // release pointer }
运行结果:
hu@xunleiman-desktop:~/tmp$ gcc t.c; ./a.out
-6552
-4
-3
-2
-1
0
1
1
4
4
4
5
5
20
50
50
70
90
999
65536