目录
整型数组排序
?浮点型数组排序:
结构体排序:
?按年龄排:
?按名字拼音排:
c库函数——qsort
是<stdlib.h>的一个库函数,作用是对数组进行排序。

- base?-- 指向要排序的数组的第一个元素的指针。
- nitems?-- 由 base 指向的数组中元素的个数。
- size?-- 数组中每个元素的大小,以字节为单位。
- compar?-- 用来比较两个元素的函数。

?compar函数要自己写,里面对两个元素进行比较,
第一个大于第二个返回1
第一个等于第二个返回0
第一个小于第二个返回-1
?qsort函数没有返回值
?例子:
整型数组排序
#include<stdio.h>
#include<stdlib.h>
int compar(const void* e1, const void* e2)
{
return (*(int*)e1 - *(int*)e2);
}
int main()
{
int arr[10] = { 9,8,7,6,5,4,3,2,1,0 };
int sz = sizeof(arr) / sizeof(arr[0]);
qsort(arr, sz, sizeof(arr[0]), compar);
int j = 0;
for (j = 0; j < sz; j++)
{
printf("%d ", arr[j]);
}
输出结果:

?浮点型数组排序:
#include<stdio.h>
#include<stdlib.h>
int compar(const void* e1, const void* e2)
{
return (*(int*)e1 - *(int*)e2);
}
int main()
{
float arr[10] = { 9.0,8.0,7.0,6.0,5.0,4.0,3.0,2.0,1.0,0.0 };
int sz = sizeof(arr) / sizeof(arr[0]);
qsort(arr, sz, sizeof(arr[0]), compar);
int j = 0;
for (j = 0; j < sz; j++)
{
printf("%0.2f ", arr[j]);
}
}
?输出结果:

结构体排序:
?按年龄排:
#include<stdio.h>
#include<stdlib.h>
struct Stu
{
char name[20];
int age;
};
int compar(const void* e1, const void* e2)
{
return(((struct Stu*)e1)->age - ((struct Stu*)e2)->age);
}
int main()
{
struct Stu s[3] = { {"张三",20},{"李四",45},{"王五",15} };
int sz = sizeof(s) / sizeof(s[0]);
qsort(s, sz, sizeof(s[0]), compar);
int j = 0;
for (j = 0; j < sz; j++)
{
printf("%s,%d ",s[j].name,s[j].age);
}
}
?输出结果:

?按名字拼音排:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct Stu
{
char name[20];
int age;
};
int compar(const void* e1, const void* e2)
{
return strcmp(((struct Stu*)e1)->name ,((struct Stu*)e2)->name);
}
int main()
{
struct Stu s[3] = { {"张三",20},{"李四",45},{"王五",15} };
int sz = sizeof(s) / sizeof(s[0]);
qsort(s, sz, sizeof(s[0]), compar);
int j = 0;
for (j = 0; j < sz; j++)
{
printf("%s,%d ",s[j].name,s[j].age);
}
}
?输出结果:

|