int cmp_int(const void* e1, const void* e2)
{
return *(int*)e1 - *(int*)e2;
}
void print(int arr[], int sz)
{
int i = 0;
for (i = 0; i < sz; i++)
{
printf("%d ", arr[i]);
}
}
void test1()
{
int arr[] = { 9,8,7,6,5,4,3,2,1,0 };
int sz = sizeof(arr) / sizeof(arr[0]);
qsort(arr, sz, sizeof(arr[0]), cmp_int);
print(arr, sz);
}
struct Stu
{
char name[20];
int age;
};
int sort_by_age(const void* e1, const void* e2)
{
return ((struct Stu*)e1)->age - ((struct Stu*)e2)->age;//要改变排序方式可以改变两个值的位置
}
int sort_by_name(const void* e1, const void* e2)
{
return strcmp(((struct Stu*)e1)->name, ((struct Stu*)e1)->name);
}
void test2()
{
struct Stu s[] = { {"zhangsan", 30},{"lisi",34},{"wangwu",20} };
//按照年龄来排序
int sz = sizeof(s) / sizeof(s[0]);
/*qsort(s, sz, sizeof(s[0]), sort_by_age);*/
//按照名字排序
qsort(s, sz, sizeof(s[0]), sort_by_name);
}
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++;
}
}
//模仿qsort实现一个冒泡排序的通用算法
void banbble_sort(void* base, int sz, int width, int (*tmp)(const void* e1, const void* e2))
{
int i = 0;
for (i = 0; i < sz - 1; i++)
{
int j = 0;
for (j = 0; j < sz - 1 - i; j++)
{
//两个元素比较
if (tmp((char*)base + j * width,(char*)base + (j + 1) * width) > 0)
{
//交换
swap((char*)base + j * width, (char*)base + (j + 1) * width, width);
}
}
}
}
void test3()
{
int arr[] = { 9,8,7,6,5,4,3,2,1,0 };
int sz = sizeof(arr) / sizeof(arr[0]);
banbble_sort(arr, sz, sizeof(arr[0]), cmp_int);
print(arr, sz);
}
void test4()
{
struct Stu s[] = { {"zhangsan", 30},{"lisi",34},{"wangwu",20} };
//按照年龄来排序
int sz = sizeof(s) / sizeof(s[0]);
/*qsort(s, sz, sizeof(s[0]), sort_by_age);*/
//按照名字排序
banbble_sort(s, sz, sizeof(s[0]), cmp_int);
}
int main()
{
/*test1();*/
/*test2();*/
/*test3();*/
test4();
return 0;
}