#includetypedef struct Stu { char name[20]; int age; } stu; void sort(void *base, int size, int width, int(*compare)(void *, void *)); int comp_int(const int *a, const int *b); int comp_double(const double *a, const double *b); int comp_stu(const stu *a, const stu *b); void sortInt() { //排序整数 int arr[7] = {3, 4, 2, 6, 8, 9, 1}; sort(arr, sizeof(arr) / sizeof(arr[0]), sizeof(arr[0]), comp_int); for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); ++i) { printf("%d ", arr[i]); } } void sortDouble() { //排序浮点数 double arrFloat[7] = {3, 4, 2, 6, 8, 9.0, 1}; sort(arrFloat, sizeof(arrFloat) / sizeof(arrFloat[0]), sizeof(arrFloat[0]), comp_double); for (int i = 0; i < sizeof(arrFloat) / sizeof(arrFloat[0]); ++i) { printf("%f ", arrFloat[i]); } } void sortStu() { //排序结构体 stu ss[3] = {{"zhang san", 100}, {"li si", 50}, {"wang wu", 60}}; sort(ss, 3, sizeof(ss[0]), comp_stu); for (int i = 0; i < sizeof(ss) / sizeof(ss[0]); ++i) { printf("[%s,%d]n", ss[i].name, ss[i].age); } } int main(void) { // sortInt(); // sortDouble(); sortStu(); return 0; } int comp_int(const int *a, const int *b) { if (*a == *b) { return 0; } else if (*a > *b) { return 1; } else { return -1; } } int comp_double(const double *a, const double *b) { if (*a == *b) { return 0; } else if (*a > *b) { return 1; } else { return -1; } } int comp_stu(const stu *a, const stu *b) { if (a->age == b->age) { return 0; } else if (a->age > b->age) { return 1; } else { return -1; } } void swap(char *p1, char *p2, int width) { int i; for (i = 0; i < width; ++i) { char tmp = *(p1 + i); *(p1 + i) = *(p2 + i); *(p2 + i) = tmp; } } void sort(void *base, int size, int width, int(*compare)(void *, void *)) { int i; int j; for (i = 0; i < size - 1; ++i) { for (j = 0; j < size - i - 1; ++j) { char *x = (char *) base + j * width; char *y = (char *) base + (j + 1) * width; if (compare(x, y) > 0) { swap(x, y, width); } } } }



