1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
| // 比较名字 bool compareName(const Student *pStu1, const Student *pStu2) { return strcmp(pStu1->name, pStu2->name) > 0; } // 比较年龄 bool compareAge(const Student *pStu1, const Student *pStu2) { return pStu1->age > pStu2->age; } // 比较成绩 bool compareScore(const Student *pStu1, const Student *pStu2) { return pStu1->score > pStu2->score; } // 交换位置 void swap(Student *pStu1, Student *pStu2) { Student temp = *pStu1; *pStu1 = *pStu2; *pStu2 = temp; } // 冒泡排序 void bubbleSort(Student *pArr, const int count, PFUNC p) { for (int i = 0; i < count; i++) { for (int j = 0; j < count - i - 1; j++) { if (p(pArr + j, pArr + j + 1)) { swap(pArr + j, pArr + j + 1); } } } } // 根据传入的参数,返回哪种函数 PFUNC getFuncName(const char *pName) { FuncName funcNames[] = { {"name", compareName}, {"age", compareAge}, {"score", compareScore} }; PFUNC p = NULL; for (int i = 0; i < sizeof(funcNames) / sizeof(*funcNames); i++) { if (strcmp(funcNames[i].name, pName) == 0) { p = funcNames[i].p; break; } } return p; } // 排序,pName 传入参数,选择根据XX排序 void sortArray(Student *pArr, const int count, const char *pName) { PFUNC p = NULL; p = getFuncName(pName); if (p != NULL) { bubbleSort(pArr, count, p); }else{ printf("函数名输入错误!\n"); } } // 遍历数组 void printArray(const Student *pArr, const int count) { for (int i = 0; i < count; i++) { printf("%s %d %.2f\n", pArr[i].name, pArr[i].age, pArr[i].score); } }
|