#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void bubble_sort(int arr[], int sz)
{
int i = 0;
for (i = 0;i < sz - 1;i++)
{
int j = 0;
for (j = 0;j <sz-1-i ;j++)
{
if (arr[j] > arr[j + 1])
{
int tmp = arr[j];
arr[j] = arr[j + 1];
arr[j+1] = tmp;
}
}
}
}
上面为整形冒泡算法实现
下面为类比qsort排序的利用回调函数的排序方法
struct stu
{
char name[20];
int 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)(void*e1,void*e2))
{
int i = 0;
//趟数
for (i = 0;i < sz;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);
}
}
}
}
int cmp_int(const void* e1, const void* e2)
{
return *(int*)e1 - *(int*)e2;
}
//使用 bubble_sort 的程序员一定知道自己排序的是什么数据
//就应该知道如何比较
void test4()
{
int arr[10] = { 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);
}
int cmp_stu_by_age(const void* e1, const void* e2)
{
return ((struct stu*)e1)->age - ((struct stu*)e2)->age;
}
//比较名字就是比较字符串
//字符串不能用><=来比较,应该用strcmp函数
int cmp_stu_by_name(const void* e1, const void* e2)
{
return strcmp(((struct stu*)e1)->name, ((struct stu*)e1)->name);
}
void test5()
{
struct stu s[3] = { {"zhangsan",20},{"wangwu",30},{"lisi",10} };
int sz = sizeof(s) / sizeof(s[0]);
bubble_sort(s, sz, sizeof(s[0]), cmp_stu_by_age);
bubble_sort(s, sz, sizeof(s[0]), cmp_stu_by_name);
}
int main()//冒泡排序
{
test4();
test5();
return 0;
}