分析:最近学习到了qsort函数,真是太方便了,据说是用快排实现的,可以对很多类型的数组进行排序,我就想自己模拟实现一个(快排还没学,而且快排实现起来比冒泡可能要麻烦一点,重要的是整理思路,就用冒泡排序模拟了一个)。
思路都在代码里面了,需要注意的点就是写swap函数的时候交换的是每个地址里面的内容而不是交换地址!
#include <stdio.h>
int sort_by_int(const void* e1, const void* e2);
void swap(char* se1, char* se2, size_t wideth);
void bubble_qsort(void* base, size_t count, size_t wideth, int (*cmp)(const void* e1, const void* e2));
int main()
{
int arr[10] = { 12,15,20,30,45,5,8,10,4,2 };
bubble_qsort(arr, 10, sizeof(arr[0]), sort_by_int);
printf("after sorted: ");
for (int i = 0; i < 10; i++)
{
printf("%d ",arr[i]);
}
}
void swap(char* se1, char* se2, size_t wideth)
{
int i = 0;
for (i = 0; i < wideth; i++)
{
char tem = 0;
tem = *se2;
*se2 = *se1;
*se1 = tem;
se1++;
se2++;
}
}
int sort_by_int(const void* e1, const void* e2)
{
return *((int*)e1) - *((int*)e2);
}
void bubble_qsort(void* base, size_t count, size_t wideth, int (*cmp)(const void* e1, const void* e2))
{
int i = 0;
for (i = 0; i < count; i++)
{
int j = 0;
for (j = 0; j < count - i - 1; j++)
{
if (cmp((char*)base + j * wideth, (char*)base + (j + 1) * wideth) > 0)
{
swap((char*)base + j * wideth, (char*)base + (j + 1) * wideth, wideth);
}
}
}
}