分享一下C語言內建的qsort 不太好記,但十分的方便XD
下面是排序身高,體重的範例~
#include <stdio.h> #include <stdlib.h> struct Student { char name[8]; float h , w; }; void InputStudent(Student *); void PrintStudent(const struct Student *px); int cmpH(const void* , const void*); int cmpW(const void* , const void*); int main() { size_t n = 0; printf("n = "); scanf("%Iu" , &n); getchar(); Student *A = (Student*)malloc(n * sizeof(Student)); int i = 0; for(i = 0 ; i < n ; i++) InputStudent(A + i); printf("Sorted by height\n"); qsort(A , n , sizeof(Student) , cmpH); for(int i = 0 ; i < n ; i++) PrintStudent(A + i); printf("Sorted by weight\n"); qsort(A , n , sizeof(Student) , cmpW); for(int i = 0 ; i < n ; i++) PrintStudent(A + i); getchar(); } void InputStudent(Student *px) { scanf("%s %f %f" , px->name , &px->h , &px->w); } void PrintStudent(const struct Student *px) { printf("Name:%s , h:%f , w:%f\n" , px->name , px->h , px->w); } int cmpH(const void *p1 , const void *p2) { const Student* ps1 = (const Student*) p1; const Student* ps2 = (const Student*) p2; return (int)(ps1->h - ps2->h); } int cmpW(const void *p1 , const void *p2) { const Student* ps1 = (const Student*) p1; const Student* ps2 = (const Student*) p2; return (int)(ps1->w - ps2->w); }
全站熱搜
留言列表