//使用回调函数实现一个通用的冒泡排序,可以排序不同的数据类型。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void swap(char *p1, char *p2, int size)
{
int i = 0;
char tmp = 0;
for (i = 0; i<size; i++)
{
tmp = *(p1 + i);
*(p1 + i) = *(p2 + i);
*(p2 + i) = tmp;
}
}
//比较整数的回调函数。
int compare_int(const void *elem1, const void *elem2)
{
return (*(int *)elem1) - (*(int *)elem2);
}
//比较字符串的回调函数。
int compare_str(const void *elem1, const void *elem2)
{
return strcmp((char *)(*(int *)elem1), (char *)(*(int *)elem2));
}
void bubble_str_int(void *base, int size, int width, int(*cmp)(const void *elem1, const void *elem2))
{
int i = 0;
int j = 0;
for (i = 0; i<size - 1; i++)
{
for (j = 0; j<size - 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()
{
char *arr_str[] = { "love","you","我","欢","喜" };
int arr_int[] = { 1,3,5,7,9,2,4,6,8,10 };
int i = 0;
int size_int = sizeof(arr_int) / sizeof(arr_int[0]);
int size_str = sizeof(arr_str) / sizeof(arr_str[0]);
bubble_str_int(arr_int, size_int, sizeof(arr_int[0]), compare_int);
printf("bubble_sort int:\n");
for (i = 0; i<size_int; i++)
{
printf("%d ", arr_int[i]);
}
printf("\n");
bubble_str_int(arr_str, size_str, sizeof(arr_str[0]), compare_str);
printf("bubble_sort string:\n");
for (i = 0; i<size_str; i++)
{
printf("%s\n", arr_str[i]);
}
system("pause");
return 0;
}