一.基本介绍
注意:qsort函数是默认从小到大排序
二、qsort 函数的使用
1.排序数组
int compare(const void* e1, const void* e2)
{return *(int*)e1 - *(int*)e2;//强制类型转换
}int main()
{int arr[10] = { 44,5,34,56,42,90,43,1,52,98 };int num = sizeof(arr) / sizeof(arr[0]);int sz = sizeof(arr[0]);qsort(&arr[0], num, sz, compare);for (int i = 0; i < num; i++){printf("%d ", arr[i]);}return 0;
}
结果:
2.排序结构体
(1)按结构体中的数字排序
struct stu
{int age;char name[20];
}arr[3];int compare(const void* e1, const void* e2)
{return ((struct stu*)e1)->age - ((struct stu*)e2)->age;//强制类型转换
}int main()
{struct stu arr[3] = { {13,"zhouzisong"},{12,"zhouzihao"},{20,"fengcheng"} };int num = sizeof(arr) / sizeof(arr[0]);int sz = sizeof(arr[0]);qsort(&arr[0], num, sz, compare);for (int i = 0; i < num; i++){printf("%d %s\n",arr[i].age,arr[i].name);}return 0;
}
结果:
(2)按结构体中的字符串排序
struct stu
{int age;char name[20];
}arr[3];int compare_by_name(const void* e1, const void* e2)
{return strcmp(((struct stu*)e1)->name , ((struct stu*)e2)->name);//强制类型转换
}int main()
{struct stu arr[3] = { {13,"zhouzisong"},{12,"zhouzihao"},{20,"fengcheng"} };int num = sizeof(arr) / sizeof(arr[0]);int sz = sizeof(arr[0]);qsort(&arr[0], num, sz, compare_by_name);for (int i = 0; i < num; i++){printf("%d %s\n",arr[i].age,arr[i].name);}return 0;
}
结果:
三、qsort 函数模拟实现
struct stu
{int age;char name[20];
}arr[3];int compare(const void* e1, const void* e2)
{return ((struct stu*)e1)->age - ((struct stu*)e2)->age;//强制类型转换
}int compare_by_name(const void* e1, const void* e2)
{return strcmp(((struct stu*)e1)->name , ((struct stu*)e2)->name);//强制类型转换
}void swap(char* bulf1, char* bulf2,int sz)
{int i;char temp;for (i = 0; i < sz; i++){temp = *bulf1;*bulf1 = *bulf2;*bulf2 = temp;bulf1++;bulf2++;}
}void my_qsort(void* base, size_t num, size_t sz, int (*cmp)(const void* e1, const void* e2))
{int i, j;for (i = 0; i < num - 1; i++){for (j = 0; j < num - 1 - i; j++){if (cmp((char*)base + j * sz, (char*)base + (j + 1) * sz) > 0){swap( (char*)base + j * sz, (char*)base + (j + 1) * sz,sz);}}}
}int main()
{struct stu arr[3] = { {13,"zhouzisong"},{12,"zhouzihao"},{20,"fengcheng"} };int num = sizeof(arr) / sizeof(arr[0]);int sz = sizeof(arr[0]);//my_qsort(&arr[0], num, sz, compare);my_qsort(&arr[0], num, sz, compare_by_name);for (int i = 0; i < num; i++){printf("%d %s\n",arr[i].age,arr[i].name);}return 0;
}