#include<stdio.h>
struct Stu
{
char name[20];
int age;
};
//自己写一个万能交换函数
void Swap(char* buf1, char* buf2,int width)
{
size_t i = 0;
for (i = 0; i < width; i++)
{
char tmp = *buf1;
*buf1 = *buf2;
*buf2 = tmp;
buf1++;
buf2++;
}
}
//自己写一个冒泡函数,使用回调函数实现一个通用的冒泡排序函数
BubbleSort(void* base, int num, size_t width, int (*cmp)(const void* e1, const void* e2))
{
int i = 0;
//趟数
for (i = 0; i < num - 1; i++)
{
//比较的对数
int j = 0;
for (j = 0; j < num - 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;
}
int cmp_float(const void* e1, const void* e2)
{
return (int)(*(float*)e1 - *(float*)e2);
}
int cmp_stu_age(const void* e1, const void* e2)
{
return ((struct Stu*)e1)->age - ((struct Stu*)e2)->age;
}
int cmp_stu_name(const void* e1, const void* e2)
{
//名字比较就是比较字符串
//字符串比较不能直接用<>=来比较,应该用strcmp来比较
return strcmp(((struct Stu*)e1)->name, ((struct Stu*)e2)->name);
}
void test_int()
{
int arr[10] = { 0,5,6,3,5,9,6,5,3,9 };
int sz = sizeof(arr) / sizeof(arr[0]);
BubbleSort(arr, sz, sizeof(arr[0]), cmp_int);
int i = 0;
for (i = 0; i < sz; i++)
{
printf("%2d ", arr[i]);
}
printf("\n");
}
void test_float()
{
float arr[10] = { 0.0,5.0,6.0,3.0,5.1,9.0,6.3,5.6,3.3,9.5 };
int sz = sizeof(arr) / sizeof(arr[0]);
BubbleSort(arr, sz, sizeof(arr[0]), cmp_float);
int i = 0;
for (i = 0; i < sz; i++)
{
printf("%f ", arr[i]);
}
printf("\n");
}
void test_stu_age()
{
struct Stu s[3] = { {"zhuangsan",20},{"lisi",21},{"wangwu",10} };
int sz = sizeof(s) / sizeof(s[0]);
BubbleSort(s, sz, sizeof(s[0]), cmp_stu_age);
int i = 0;
for (i = 0; i < sz; i++)
{
printf("%s ", (&s[i])->name);
printf("%d ", (&s[i])->age);
}
printf("\n");
}
void test_stu_name()
{
struct Stu s[3] = { {"zhuangsan",20},{"lisi",21},{"wangwu",10} };
int sz = sizeof(s) / sizeof(s[0]);
BubbleSort(s, sz, sizeof(s[0]), cmp_stu_name);
int i = 0;
for (i = 0; i < sz; i++)
{
printf("%s ", (&s[i])->name);
printf("%d ", (&s[i])->age);
}
printf("\n");
}
int main()
{
test_int();
test_float();
test_stu_age();
test_stu_name();
return 0;
}