1、
1.1
#include <stdio.h> #include <string.h> #define NUMBER 5 #define NAME_LEN 64 typedef struct{ char name[NAME_LEN]; int height; float weight; long schols; }Student; void swap(Student *x, Student *y) { Student tmp = *x; *x = *y; *y = tmp; } void sort(Student x[], int n) { int i, j; for(i = 0; i < n - 1; i++) { for(j = n - 1; j > i; j--) { if(x[j - 1].height > x[j].height) { swap(&x[j - 1], &x[j]); } } } } int main(void) { int i; Student stu[NUMBER]; for(i = 0; i < NUMBER; i++) { printf("NO.%d.name = ", i + 1); scanf("%s", stu[i].name); printf("NO.%d.height = ", i + 1); scanf("%d", &stu[i].height); printf("NO.%d.weight = ", i + 1); scanf("%f", &stu[i].weight); printf("NO.%d.schols = ", i + 1); scanf("%ld", &stu[i].schols); } for(i = 0; i < NUMBER; i++) { printf("%-8s %7d %7.2f %7ld ", stu[i].name, stu[i].height, stu[i].weight, stu[i].schols); } sort(stu, NUMBER); puts(" ================================ "); for(i = 0; i < NUMBER; i++) { printf("%-8s %7d %7.2f %7ld ", stu[i].name, stu[i].height, stu[i].weight, stu[i].schols); } return 0; }
1.2
#include <stdio.h> #include <string.h> #define NUMBER 5 #define NAME_LEN 64 typedef struct{ char name[NAME_LEN]; int height; float weight; long schols; }Student; void swap(Student *x, Student *y) { Student tmp = *x; *x = *y; *y = tmp; } void sort_int(Student x[], int n) { int i, j; for(i = 0; i < n - 1; i++) { for(j = n - 1; j > i; j--) { if(x[j - 1].height > x[j].height) { swap(&x[j - 1], &x[j]); } } } } void sort_str(Student x[], int n) { int i, j; for(i = 0; i < n - 1; i++) { for(j = n - 1; j > i; j--) { if(strcmp(x[j - 1].name,x[j].name) > 0) { swap(&x[j - 1], &x[j]); } } } } int main(void) { int i; Student stu[NUMBER]; for(i = 0; i < NUMBER; i++) { printf("NO.%d.name = ", i + 1); scanf("%s", stu[i].name); printf("NO.%d.height = ", i + 1); scanf("%d", &stu[i].height); printf("NO.%d.weight = ", i + 1); scanf("%f", &stu[i].weight); printf("NO.%d.schols = ", i + 1); scanf("%ld", &stu[i].schols); } for(i = 0; i < NUMBER; i++) { printf("%-8s %7d %7.2f %7ld ", stu[i].name, stu[i].height, stu[i].weight, stu[i].schols); } int j; puts("choose: j = 1, sort by height; j = 2, sort by name."); printf("j = "); scanf("%d", &j); switch(j) { case 1: sort_int(stu, NUMBER); break; case 2: sort_str(stu, NUMBER); break; } puts(" ================================ "); for(i = 0; i < NUMBER; i++) { printf("%-8s %7d %7.2f %7ld ", stu[i].name, stu[i].height, stu[i].weight, stu[i].schols); } return 0; }