qsort函数的使用
通过模拟qsort函数希望能帮助大家更深入的了解qsort函数的实现逻辑
1.根据参数先写好程序主体
void bu_sort(void* base, size_t sz, size_t width, int (*cmp)(const void* e1, const void* e2))
{
//趟数
size_t i = 0;
for (i = 0; i < sz - 1; i++)
{
//一趟冒泡排序的过程
size_t j = 0;
for (j = 0; j < sz - 1 - i; j++)
{
if (cmp( (char*)base + j * width, (char*)base + (j + 1) * width ) > 0)
{
//交换
Swap((char*)base + j * width, (char*)base + (j + 1) * width, width);
}
}
}
}
2.写交换函数
void Swap(char* buf1, char* buf2, int width)
{
int i = 0;
for (i = 0; i < width; i++)
{
char tmp = *buf1;
*buf1 = *buf2;
*buf2 = tmp;
buf1++;
buf2++;
}
}
3.用户自己写好cmp函数
#define _CRT_SECURE_NO_WARNINGS 1
struct stu
{
char name[20];
float GPA;
};
int cmp_str(const void* e1, const void* e2)
{
return strcmp((char*)e1, (char*)e2);
}
int cmp_str_len(const void* e1, const void* e2)
{
return strlen((char*)e1) - strlen((char*)e2);
}
int cmp_struct_stu_name(const void* e1, const void* e2)
{
return strcmp( ((struct stu*)e1)->name, ((struct stu*)e2)->name );
}
int cmp_struct_stu_GPA(const void* e1, const void* e2)
{
return ( ((struct stu*)e2)->GPA - ((struct stu*)e1)->GPA );
}
4.调用函数
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void my_swap(char* buf1, char* buf2, int width)
{
int i = 0;
for (i = 0; i < width; i++)
{
char tmp = *buf1;
*buf1 = *buf2;
*buf2 = tmp;
buf1++;
buf2++;
}
}
void bu_sort(void* base, size_t sz, size_t width, int (*cmp)(const void* e1, const void* e2))
{
//趟数
size_t i = 0;
for (i = 0; i < sz - 1; i++)
{
//一趟冒泡排序的过程
size_t j = 0;
for (j = 0; j < sz - 1 - i; j++)
{
if (cmp( (char*)base + j * width, (char*)base + (j + 1) * width ) > 0)
{
//交换
my_swap((char*)base + j * width, (char*)base + (j + 1) * width, width);
}
}
}
}
typedef struct stu
{
char name[20];
float GPA;
}stu;
int compare_str(const void* e1, const void* e2)
{
return strcmp((char*)e1, (char*)e2);
}
int cmp_str_len(const void* e1, const void* e2)
{
return strlen((char*)e1) - strlen((char*)e2);
}
int cmp_struct_stu_name(const void* e1, const void* e2)
{
return strcmp(((struct stu*)e1)->name, ((struct stu*)e2)->name);
}
int cmp_struct_stu_GPA(const void* e1, const void* e2)
{
return (((struct stu*)e2)->GPA - ((struct stu*)e1)->GPA);
}
int main()
{
int i = 0;
stu s[3] = { {"zhangsan",3.4} ,{"zhangmazi",4.0} ,{"dingzhen",1.0} };
bu_sort(s, 3, sizeof(s[0]), cmp_struct_stu_name);
for (i = 0; i < 3; i++)
{
printf("%s %f\n", s[i].name, s[i].GPA);
}
bu_sort(s, 3, sizeof(s[0]), cmp_struct_stu_GPA);
for (i = 0; i < 3; i++)
{
printf("%s %f\n", s[i].name, s[i].GPA);
}
}