void swap(char* buf1, char* buf2, int width)
{
int i = 0;
for (i = 0; i < width; i++)
{
int temp = *buf1;
*buf1 = *buf2;
*buf2 = temp;
buf1++;
buf2++;
}
}
void cmp_int(const void* e1,const void* e2)
{
return *(int*)e1 - *(int*)e2;
}
void bubble_sort(void* base, int sz, int width, int (*cmp)(void* e1, void* e2))
{
int i = 0;
for (i = 0; i < sz - 1; i++)
{
int 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);
}
}
}
}
void test_int_1()
{
int arr[] = { 9,8,7,6,5,4,3,2,34,65,23,56 };
int sz = sizeof(arr) / sizeof(arr[0]);
bubble_sort(arr, sz, sizeof(arr[0]), cmp_int);
int i = 0;
for (i = 0; i < sz; i++)
{
printf("%d ", arr[i]);
}
}
struct stu
{
char name[20];
int age;
double socer;
};
void cmp_stu(const void* e1, const void* e2)
{
return ((struct stu*)e1)->age - ((struct stu*)e2)->age;
}
void test_stu_2()
{
struct stu s[3] = { {"zhangsan",24,80.2},{"lisi",25,82.3},{"wangwu",22,91.2} };
int sz = sizeof(s) / sizeof(s[0]);
bubble_sort(s, sz, sizeof(s[0]), cmp_stu);
int i = 0;
for (i = 0; i < sz; i++)
{
printf("%d ", s[i].age);
}
}
int main()
{
//test_int_1();
test_stu_2();
return 0;
}