C语言qsort简单使用
qsort函数位于stdlib.h头文件里。是用来排序的函数,函数原型如下:
void qsort(void *ptr, size_t count, size_t size, int (*comp)(const void *, const void *));
四个参数:
ptr:指向待排序数组的指针
count:数组元素的数目
size:数组中每个元素所占的字节数
comp:函数指针,指向比较元素大小的函数。如果第一个小于第二个,返回负值,第一个大于第二个,返回正值,相等返回0,函数签名等价于如下的形式:
int cmp(const void *a, const void *b);
下面是示例代码,分别对int数组和结构体数组进行排序:
#include <stdio.h> #include <stdlib.h> typedef struct myStructure { int ID; char name[10]; } myStructure; int compareStruct(const void *left, const void *right); int compareNum(const void *left, const void *right); int main() { myStructure structureArr[5] = { {1, "a"}, {5, "e"}, {3, "c"}, {4, "d"}, {2, "b"}}; printf("before sort: "); for (int i = 0; i < 5; i++) { printf("ID = %d,name = %s ", structureArr[i].ID, structureArr[i].name); } printf("after sort: "); qsort(&structureArr, 5, sizeof(myStructure), compareStruct); for (int i = 0; i < 5; i++) { printf("ID = %d,name = %s ", structureArr[i].ID, structureArr[i].name); } int arr[5] = {2, 5, 6, 4, 3}; printf("before sort: "); for (int i = 0; i < 5; i++) { printf("%d ", arr[i]); } qsort(arr, 5, sizeof(int), compareNum); printf("after sort: "); for (int i = 0; i < 5; i++) { printf("%d ", arr[i]); } system("pause"); return 0; } int compareStruct(const void *left, const void *right) { myStructure *leftstructure = (myStructure *)left; myStructure *rightstructure = (myStructure *)right; if (leftstructure->ID < rightstructure->ID) { return -1; } if (leftstructure->ID > rightstructure->ID) { return 1; } if (leftstructure->ID == rightstructure->ID) { return 0; } } int compareNum(const void *left, const void *right) { int leftNum = *(int *)left; int rightNum = *(int *)right; if (leftNum < rightNum) { return -1; } if (leftNum > rightNum) { return 1; } if (leftNum == rightNum) { return 0; } }