函数名称:qsort,在头文件:<stdlib.h>中
#include <stdio.h>
#include <stdlib.h>
int cmp(const void *a,const void *b)
{
return *(int *)a-*(int *)b;//这是从小到大排序,若是从大到小改成: return *(int *)b-*(int *)a;
}
int main()
{
int a[100];
int n;
scanf("%d",&n);//n代表数组中有几个数字
int i;
for(i=1;i<=n;i++)
scanf("%d",&a[i-1]);
qsort(a,n,sizeof(a[0]),cmp);//(数组,需要排序的数字个数,单个数字所占内存大小,比较函数)
for(i=1;i<=n;i++)
printf("%d ",a[i-1]);
return 0;
}
对二维数组
int cmp(const void* a, const void* b)
{
return ((int*)a)[1] - ((int*)b)[1];
//1可以改为其他元素
}
qsort(arr, n, 2 * sizeof(kid[0][0]), cmp);
//n代表二维数组行数,2代表二维数组的每个子数组元素个数
对结构体
typedef struct {
int id;
char name[20];
int age;
} Person;
int cmp(const void *a, const void *b) {
Person *pa = (Person *)a;
Person *pb = (Person *)b;
return pa->id - pb->id;
}
int main() {
Person people[3] = { {3, "C", 30}, {1, "A", 20}, {2, "B", 25} };
int size = sizeof(people) / sizeof(Person);
qsort(people, size, sizeof(Person), cmp);
for (int i = 0; i < size; i++) {
printf("id:%d, name:%s, age:%d\n", people[i].id, people[i].name, people[i].age);
}
return 0;
}