编写一个冒泡排序,既可以编写字符串也可以编写数字。
1).需要实现一个函数指针,在排序的时候将函数的入口地址传进来。
void sort(void *base, int len, int width, int(*cmp)(const void*, const void*))
{
assert(base);
int i = 0;
int j = 0;
for (i = 0; i < len; i++)
{
for (j = 0; j < len - 1 - j; j++)
{
if (cmp((char *)base + width*j, (char *)base + width*(j + 1))>0)
{
swap((char *)base + width*j, (char *)base + width*(j + 1), width);
}
}
}
}
实现代码的主逻辑
1).参数设置,一个可以接收任何类型的指针,数据大小,类型大小,函数声明。
2).需要实现一个比较字符串函数,整型比较函数,交换函数。
比较字符串函数
int str_cmp(const void *p1, const void *p2)
{
assert(p1);
assert(p2);
return strcmp((char *)(*(int *)p1), (char *)(*(int *)p2));
}
比较整型的函数
int int_cmp(const void *p1, const void *p2)
{
assert(p1);
assert(p2);
if (*(int *)p1 > *(int *)p2)
{
return 1;
}
else if (*(int *)p1 == *(int *)p2)
{
return 0;
}
else
{
return -1;
}
}
交换函数的实现
void swap(void *p1, void *p2, int size)
{
assert(p1);
assert(p2);
int i = 0;
for (i = 0; i < size; i++)
{
char tmp = *((char *)p1 + i);
*((char *)p1 + i) = *((char *)p2 + i);
*((char *)p2 + i) = tmp;
}
}
当需要比较字符串的时候,传参的时候需要将str_cmp传进来。同理需要比较整型数字,需要将int_cmp传进来,请注意函数参数。
以上就是本人在学习过程中的一些经验总结。当然,本人能力有限,难免会有纰漏,希望大家可以指正。
转载于:https://blog.51cto.com/10799170/1718853