one.
int数组排序 #include<iostream> #include<cstdio> #include<cstdlib> #include<cstring> #include<cmath> #include<algorithm> using namespace std; const int maxn=1007; const int INF=0x3f3f3f3f; int a[maxn]; int cmp(const void *a, const void *b) { return *(int *)a-*(int *)b; } int main() { int n; scanf("%d", &n); for(int i=0; i<n; i++) scanf("%d", &a[i]); qsort(a, n, sizeof(a[0]), cmp); for(int i=0; i<n; i++) printf("%d%c", a[i], i==n-1?' ':' '); return 0; }
two.
double数组排序 #include<iostream> #include<cstdio> #include<cstdlib> #include<cstring> #include<cmath> #include<algorithm> using namespace std; const int maxn=1007; const int INF=0x3f3f3f3f; double a[maxn]; int cmp(const void *a, const void *b) { return *(double *)a-*(double *)b; } int main() { int n; scanf("%d", &n); for(int i=0; i<n; i++) scanf("%lf", &a[i]); qsort(a, n, sizeof(a[0]), cmp); for(int i=0; i<n; i++) printf("%lf%c", a[i], i==n-1?' ':' '); return 0; }
three.
对字符数组排序 #include<iostream> #include<cstdio> #include<cstdlib> #include<cstring> #include<cmath> #include<algorithm> using namespace std; const int maxn=1007; const int INF=0x3f3f3f3f; char s[maxn]; int cmp(const void *a, const void *b) { return *(char *)a-*(char *)b; } int main() { int n; scanf("%s", s); n=strlen(s); qsort(s, n, sizeof(s[0]), cmp); printf("%s ", s); return 0; }
four.
对结构体排序 #include<iostream> #include<cstdio> #include<cstdlib> #include<cstring> #include<cmath> #include<algorithm> using namespace std; const int maxn=1007; const int INF=0x3f3f3f3f; struct node { double x; }s[maxn]; int cmp(const void *a, const void *b) { struct node *c=(struct node *)a; struct node *d=(struct node *)b; return c->x<d->x?1:-1; } int main() { int n; scanf("%d", &n); for(int i=0; i<n; i++) scanf("%lf", &s[i].x); qsort(s, n, sizeof(s[0]), cmp); for(int i=0; i<n; i++) printf("%f%c", s[i].x, i==n-1?' ':' '); return 0; }