#include
#include
void my_bubblesort(void* base, int num, int width, int (*cmp)(const void* e1, const void* e2));
int cmp_int(const void* e1, const void* e2)
{
return *(int*)e1 - *(int*)e2;
}
int cmp_char(const void* e1, const void* e2)
{
return *(char*)e1 - *(char*)e2;
}
int cmp_str(const void* e1, const void* e2)
{
return *(char*)e1 - *(char*)e2;
}
int cmp_float(const void* e1, const void* e2)
{
return (*(float*)e1 > *(float*)e2) ? 1 : -1;
}
void test_int()
{
int arr[10] = { 1,3,5,7,9,2,4,6,8,10 };
int sz = sizeof(arr) / sizeof(arr[0]);
my_bubblesort(arr, sz, sizeof(arr[0]), cmp_int);
int i;
for (i = 0; i < sz; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
}
void test_char()
{
char ch[20] = "dfhqodna";
int sz = strlen(ch);
my_bubblesort(ch, sz, 1, cmp_char);
int i;
for (i = 0; i < sz; i++)
{
printf("%c", ch[i]);
}
printf("\n");
}
void test_str()
{
char str[3][20] = { "zhangsan", "lisi", "wangwu" };
int sz = sizeof(str) / sizeof(str[0]);
my_bubblesort(str, sz, sizeof(str[0]), cmp_str);
int i;
for (i = 0; i < sz; i++)
{
printf("%s ", str[i]);
}
printf("\n");
}
void test_float()
{
float arr[5] = { 3.5, 1.5, 3.5, 3.2, 5.3 };
int sz = sizeof(arr) / sizeof(arr[0]);
my_bubblesort(arr, sz, sizeof(arr[0]), cmp_float);
int i;
for (i = 0; i < sz; i++)
{
printf("%.1lf ", arr[i]);
}
printf("\n");
}
void Swap(char* buf1, char* buf2, int width)
{
int i;
for (i = 0; i < width; i++)
{
char tmp = *buf1;
*buf1 = *buf2;
*buf2 = tmp;
buf1++;
buf2++;
}
}
void my_bubblesort(void* base, int num, int width, int (*cmp)(const void* e1, const void* e2))
{
int i, j;
for (i = 0; i < num - 1; i++)
{
for (j = 0; j < num - 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 main()
{
test_int();
test_char();
test_str();
test_float();
return 0;
}