### qsort的模拟实现

``````#include <stdio.h>
void Swap(char* buf1, char* buf2, int width)
{
int i = 0;
char tmp = 0;
for (i = 0; i < width; i++)
{
tmp = *buf1;
*buf1 = *buf2;
*buf2 = tmp;
buf1++;
buf2++;
}
}
//写出冒泡排序的程序员是不知道即将到来需要排序的数组是哪种类型的
void bubble_sort(void* base, int sz, int width, int (*cmp)(const void* e1, const void* e2))
{
int i = 0;
int j = 0;
for (i = 0; i < sz - 1; i++)
//比较的趟数
{
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);
}
}
}
}
int cmp_int(const void* e1, const void* e2)
{
return *(int*)e1 - *(int*)e2;
}
void test1()
{
int arr[] = { 9,8,7,6,5,4,3,2,1,0 };
int sz = sizeof(arr) / sizeof(arr[0]);
bubble_sort(arr, sz, sizeof(arr[0]), cmp_int);
//模拟qsort的实现依然是建立在，使用该函数的人知道自己需要比较的数据类型
//并且自己能够写出对应的比较函数
int i = 0;
for (i = 0; i < sz; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
}
struct Stu
{
char name[20];
int age;
};
int com_stu_by_age(const void* e1, const void* e2)
{
return ((struct Stu*)e1)->age - ((struct Stu*)e2)->age;
}
int com_stu_by_name(const void* e1, const void* e2)
{
return strcmp(((struct Stu*)e1)->name, ((struct Stu*)e2)->name);
}
void test2()
{
struct Stu s[3] = { {"zhangsan",60},{"lisi",40},{"wangwu",50} };
int sz = sizeof(s) / sizeof s[0];
bubble_sort(s, sz, sizeof(s[0]), com_stu_by_age);
int i = 0;
for (i = 0; i < sz; i++)
{
printf("%d ", *(&s[i].age));
}
printf("\n");
bubble_sort(s, sz, sizeof(s[0]), com_stu_by_name);
int j = 0;
for (j = 0; j < sz; j++)
{
printf("%s ", &s[j].name);
}
}

int main()
{
test1();
test2();
return0;
}
``````