/*
模仿qsort 实现冒泡排序通用算法
*/
cmp_int(const void* e1, const void* e2)
{
//因为参数是void*,所以不能直接解引用
return *(int*)e1 - *(int*)e2;
}
//打印
void print_arr(int arr[], int sz)
{
int i = 0;
for ( i = 0; i < sz; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
}
//交换
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;
for (i = 0; i < sz; i++)
{
//一趟的排序
int j = 0;
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);
}
}
}
}
int main()
{
int arr[] = { 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);
//打印
print_arr(arr, sz);
return 0;
}