谁说只有C++才可以实现泛型,C照样也是可以的,废话少说,上代码
/**
* c实现泛型排序
* 示例是用泛型实现数字,字符串的排序
**/
#include <stdio.h>
/**/
#define SORT_INIT(T, name)\
void sort_##name(T *array, int num, int (*SortFunc)(T a, T b))\
{\
int i = 1;\
int k = 0;\
T temp;\
for(i = 1; i < num; i ++)\
{\
for(k = i; k > 0; k --)\
{\
if(SortFunc(array[k - 1], array[k]) > 0)\
{\
temp = array[k];\
array[k] = array[k - 1];\
array[k - 1] = temp;\
}\
}\
}\
}
/*定义整数比较函数*/
int compare_int(int a, int b)
{
if(a < b)
return -1;
if(a == b)
return 0;
return 1;
}
/*定义字符串比较函数*/
int compare_str(char *a, char *b)
{
return strcmp(a, b);
}
/*整数排序*/
SORT_INIT(int, int)
/*字符串排序*/
SORT_INIT(char*, str);
int array[] = {2, 4, 7, 3, 8, 0, 4, 7, 2, 5, 6};
char* array2[] = {"123", "345", "asd", "edfg", "dfg"};
/**/
int main(int argc, char **argv)
{
int num = sizeof(array) / sizeof(int);
int i = 0;
int num2 = sizeof(array2) / sizeof(char*);
/*整数排序*/
sort_int(array, num, compare_int);
/*字符串排序*/
sort_str(array2, num2, compare_str);
for(; i < num; i ++)
{
printf("%d ", array[i]);
}
printf("\n");
for(i = 0; i < num2; i ++)
printf("%s ", array2[i]);
printf("\n");
return 0;
}