定义:
泛型编程(Generic Programming) 指在多种数据类型上皆可操作。和面向对象编程不同,它并不要求额外的间接层来调用函数,而是使用完全一般化并可重复使用的算算效率与针对某特定数据类型而设计的算法相同。
一些碎碎念:相比C++,C语言的泛用性很差,这里强行用C语言实现了冒泡排序,说实在我也没太吃透这玩意,还是C++泛用性高,真香
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define VALUE 0.0000001
typedef int (*Fun)(void *, void *); //PFun函数指针数据类型
int int_cmp(void *vp1, void *vp2)
{
return *(int *)vp1 - *(int *)vp2;
}
int double_cmp(void *vp1, void *vp2)
{
double tmp = *(double *)vp1 - *(double *)vp2;
if (tmp >= VALUE)
{
return 1;
}
else if (tmp <= -VALUE)
{
return -1;
}
else
{
return 0;
}
}
int char_cmp(void *vp1, void *vp2)
{
return *(char *)vp1 - *(char *)vp2;
}
int str_cmp(void *vp1, void *vp2)
{
return strcmp(*(char **)vp1, (*(char **)vp2));
}
void Swap(void *vp1, void *vp2, int size)
{
void *tmp = malloc(size);
memcpy(tmp, vp1, size);
memcpy(vp1, vp2, size);
memcpy(vp2, tmp, size);
free(tmp);
}
//arr:数组首地址;len:数组长度;elemsize:每个元素的字节数,pcmp对应类型的比较函数的指针
void bubble(void *arr, int len, int elemsize, Fun pcmp)
{
int flag; //标记是否发生了数据交换,若无交换则已经处于有序状态,无需再往下进行遍历
void *base;
void *base_next;
for (int i = 0; i < len - 1; i++)
{
flag = 0;
for (int j = 0; j < len - i - 1; j++)
{
base = (char *)arr + j * elemsize;
base_next = (char *)arr + (j + 1) * elemsize;
if (pcmp(base, base_next) > 0)
{
Swap(base, base_next, elemsize);
flag = 1;
}
}
if (flag == 0)
{
break; //没有进行交换,已有序
}
}
}
int main()
{
//定义四个数组存放四种不同的数据类型
int irr[] = {9, 24, 62, 13, 4, 16, 55, 2, 29, 10};
double drr[] = {54.3, 23.3f, 47.24, 16.8f, 6.26, 78.f};
char crr[] = {'c', 'e', 'z', 'd', 'a', 'g', 'b'};
const char *srr[] = {"gsda", "qw", "gbfi", "Hfw", "QFE", "mu", "Ruy"}; //大写字母排在前
bubble(irr, sizeof(irr) / sizeof(irr[0]), sizeof(int), int_cmp); //整型数组排序测试
for (int i = 0; i < sizeof(irr) / sizeof(irr[0]); i++)
{
printf("%d ", irr[i]);
}
printf("\n");
bubble(drr, sizeof(drr) / sizeof(drr[0]), sizeof(double), double_cmp); //浮点数(float、double)型数组排序测试-
for (int i = 0; i < sizeof(drr) / sizeof(drr[0]); i++)
{
printf("%g ", drr[i]); //%g自动调整小数显示位数
}
printf("\n");
bubble(crr, sizeof(crr) / sizeof(crr[0]), sizeof(char), char_cmp); //字符型数组排序测试
for (int i = 0; i < sizeof(crr) / sizeof(crr[0]); i++)
{
printf("%c ", crr[i]);
}
printf("\n");
bubble(srr, sizeof(srr) / sizeof(srr[0]), sizeof(char *), str_cmp); //字符串型数组排序测试
for (int i = 0; i < sizeof(srr) / sizeof(srr[0]); i++)
{
printf("%s ", srr[i]);
}
printf("\n");
return 0;
}