#include<stdlib.h>
#include<string.h>
#include<stdio.h>
struct Stu {
char name[20];
int age;
};
//比较函数
int cmp_int(const void* e1, const void* e2) {
return (*(int*)e1 - *(int*)e2);
}
//比较函数
int cmp_stu_by_age(const void* e1, const void* e2) {
return ((struct Stu*)e1)->age - ((struct Stu*)e2)->age;
}
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++;
}
}
void bubble_sort(void *base, int sz, int width, int(*cmp)(const void *e1, const void *e2)) {
int i = 0, j = 0;
int flag = 1;
int tmp = 0;
for (i = 0;i < sz - 1;i++) {
for (j = 0; j < sz - i - 1; j++) {
if (cmp((char*)base+j*width,(char*)base+(j+1)*width)>0) {
//交换
Swap((char*)base + j * width, (char*)base + (j + 1) * width, width);
flag = 0;
}
/*if (arr[j] > arr[j + 1]) {
tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
flag = 0;
}*/
}
if (flag == 1) {
break;
}
}
}
void text1() {
int arr[] = { 9,1,2,8,7,6,5,4,0,3 };
int sz = sizeof(arr) / sizeof(arr[0]);
int i = 0;
bubble_sort(arr, sz, sizeof(arr[0]), cmp_int);
for (i = 0;i < sz;i++) {
printf("%d ", arr[i]);
}
}
void text2() {
struct Stu s1[] = { {"zhangsan",25}, {"lisi",21},{"wangwu",26}};
int sz = sizeof(s1) / sizeof(s1[0]);
bubble_sort(s1, sz, sizeof(s1[0]), cmp_stu_by_age);
int i = 0;
for (i = 0;i < sz;i++) {
printf("%s %d ", s1[i].name, s1[i].age);
}
}
int main() {
text1();
printf("\n");
text2();
return 0;
}
其中Swap()函数是交换函数,cmp_int()和cmp_stu_by_age()是比较函数,bubble_sort()是函数主体。
text1()是对数组进行冒泡排序
text2()是对结构体的age进行冒泡排序