qsort排序
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <string.h>
int com_num(const void* n1, const void* n2) {
return *(int*)n1 - *(int*)n2;
}
void test1() {
int arr[] = { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };
int sz = sizeof(arr) / sizeof(arr[0]);
qsort(arr, sz, sizeof(arr[0]), com_num);
for (int i = 0;i < sz;i++) {
printf("%d ", arr[i]);
}
}
struct Student
{
char name[10];
int age;
};
int com_age(const void* s1, const void * s2)
{
return ((struct Student*)s1)->age - ((struct Student*)s2)->age;
}
int com_name(const void* s1, const void* s2)
{
return strcmp(((struct Student*)s1)->name, ((struct Student*)s2)->name);
}
void test2()
{
struct Student stu[3] = { {"zhangsan", 29},{"lisi", 22},{"wangwu", 21} };
int sz = sizeof(stu) / sizeof(stu[0]);
//qsort(stu, sz, sizeof(stu[0]), com_age);
qsort(stu, sz, sizeof(stu[0]), com_name);
for (int i = 0; i < sz; i++)
{
printf("%s %d\n",stu[i].name, stu[i].age);
}
}
//快排 qsort
int main() {
// test1();
test2();
return 0;
}
网友评论