快速排序函數函數原型:數組
void qsort(void *base, size_t num, size_t width, int(*compare)(const void *num1, const void *num2));ide
參數:一、待排序的數組的首地址函數
二、數組中待排序元素的個數
spa
三、各元素佔用空間的大小
指針
四、指向比較函數的指針,用於肯定排序的順序
orm
compare函數的原型:int compare(const void *elem1,const void *elem2)blog
compare函數的返回值 | 描述 |
小於0 | elem1將排在elem2的前面 |
等於0 | elem1等於elem2 |
大於0 | elem1將排在elem2的後面 |
一、×××數組的比較函數:排序
/*×××數組比較函數*/ int IntCmp(const void *a, const void *b) { return (*(int *)a > *(int *)b) ? 1 : -1; }
二、浮點型數組比較函數字符串
/*浮點型數組比較函數*/ int DoubleCmp(const void *a, const void *b) { return ((*(double *)a - *(double *)b)>0) ? 1 : -1; }
三、字符型數組比較函數get
/*字符型數組比較函數*/ int CharCmp(const void *a, const void *b) { return (*(char *)a > *(char *)b) ? 1 : -1; }
四、字符串數組比較函數
/*字符串數組比較函數*/ int StrCmp(const void *str1, const void *str2) { return (strcmp((char *)(*(int *)str1), (char *)(*(int *)str2)) > 0) ? 1 : -1; }
五、結構體類型比較函數,假設有如下結構體,並以學生成績爲依據對學生姓名按照成績的必定順續輸出
#include <stdio.h> #include <stdlib.h> /*學生類型的結構體*/ typedef struct Stu { char name[20];//學生姓名 int sorce; //學生成績 }Stu; /*結構體類型比較函數*/ int StcCmp(const void *stc1, const void *stc2) { return ((*(Stu *)stc1).sorce > (*(Stu *)stc2).sorce) ? 1 : -1; } int main() { Stu stu[] = { { "lisi", 70 }, { "zhangsan", 35 }, { "wangwu", 50 } }; qsort(stu, sizeof(stu) / sizeof(stu[0]), sizeof(stu[0]), StcCmp); for (int i = 0; i < sizeof(stu) / sizeof(stu[0]); i++) { printf("%s\n", stu[i].name); } system("pause"); return 0; }
結構體類型排序運行結果: