C语言——使用回调函数模拟实现qsort

同学们还记得之前我们已经学过一种排序方法叫“冒泡排序“嘛。代码直接附上咯


void bubble_sort(int arr[], int sz)
{
	int i = 0;//趟数
	for (i = 0; i < sz-1; i++)
	{
		int j = 0;
		for (j = 0; j < sz-i-1; j++)
		{
			if (arr[j] > arr[j + 1])
			{
				int tmp = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = tmp;
			}
		}
	}
}
 
int main()
{
	int arr[] = { 6,4,1,2,9,3,7,8,10,5 };
	int sz = sizeof(arr) / sizeof(arr[0]);
 
	bubble_sort(arr,sz);
 
	//打印
	for (int i = 0; i < sz; i++)
	{
		printf("%d ", arr[i]);
	}
	return 0;
}

 现在我们已经找到了一些相应的问题,那我们怎么改造呢?

我们先参考学习一下库函数qsort或许你就会有自己的思路了,qsort的头文件<stdlib.h>

已经了解qsort需要包含的元素,那函数指针指向的比较函数我们要怎么去写呢,这边Mr.狠人举个例子哈

当然这样写是为了让你更好理解,如果能理解的话那我们可以简化代码

//自定义比较函数
int compar(const void* e1,const void* e2)
{
	return *(int*)e1 - *(int*)e2;
}

int main()
{
	int arr[10] = { 3,1,9,8,5,4,0,2,7,6 };
	int sz = sizeof(arr) / sizeof(arr[0]);
	qsort(arr, sz, sizeof(arr[0]), compar);
	
	//打印
	for (int i = 0; i < sz; i++)
	{
		printf("%d ", arr[i]);
	}
	
	return 0;
}

 当然我们也可以测试一下结构体数据能不能用qsort来排序

//创建一个结构体
struct students
{
	char name[20];
	int age;
};

//比较函数
int compar_students_by_age(const void* e1, const void* e2)
{
	return (*(struct students*)e1).age - (*(struct students*)e2).age;
}

int main()
{
	//为了方便理解我们就不演示回调函数,大家使用回调函数肯定更好
	struct students classA[3] = { {"jason",18},{"jack",28},{"leon",33} };
	int sz = sizeof(classA) / sizeof(classA[0]);
	qsort(classA, sz, sizeof(classA[0]), compar_students_by_age);
	
	//打印
	for (int i = 0; i < sz; i++)
	{
		printf("%d %s\n", classA[i].age,classA[i].name);
	}
	
	return 0;
}

当然我们也可以不按照age来比,我们用name来比,字符串的比较方式用strcmp函数比较

//创建一个结构体
struct students
{
	char name[20];
	int age;
};

//比较函数
//字符串的比较不能直接用大于号小于号
int compar_students_by_name(const void* e1, const void* e2)
{
	return strcmp((*(struct students*)e1).name,(*(struct students*)e2).name);
}

int main()
{
	struct students classA[3] = { {"jason",18},{"jack",28},{"leon",33} };
	int sz = sizeof(classA) / sizeof(classA[0]);
	qsort(classA, sz, sizeof(classA[0]), compar_students_by_name);
	
	//打印
	for (int i = 0; i < sz; i++)
	{
		printf("%d %s\n", classA[i].age,classA[i].name);
	}
	
	return 0;
}

 现在我们已经学会了qsort的使用方法,那么有没有思路去改造我们的冒泡排序了?还是把这张图拿下来哈

我们参考过qsort,我们是不是可以跟他一样用void*指针去接收所有类型的变量的地址

接下来是不是就要解决比较的问题,我们不知道使用者会传来的是什么类型的数组,可能是结构体对吧,那就不难单纯的用大于号小于号去比较

 那现在我们的冒泡排序的参数是不是就变成这样了

void bubble_sort(void* base, int sz, int width, int(*compar)(const void* e1, const void* e2))

比较函数的调用就是这样

int i = 0;//趟数
for (i = 0; i < sz - 1; i++)
{
	int j = 0;
	for (j = 0; j < sz - i - 1; j++)
	{
		//我们在这边已经有宽度了,那是不是全用char类型就行,因为char类型是一个字节,乘宽度刚好是我们需要的大小
		if(compar((char*)base+j*width, (char*)base + (j+1) * width)>0)//调用比较函数
		{
			//交换
		}
	}
}

现在就剩下交换了

那我们写个函数进行元素交换吧

    Swap((char*)base + j * width, (char*)base + (j + 1) * width, width);

//交换函数
//调用时就已经强制转换成char*,所以这边直接写char*就行
void Swap(char* buf1, char* buf2, int width)
{
	for (int i = 0; i < width; i++)
	{
		char tmp = *buf1;
		*buf1 = *buf2;
		*buf2 = tmp;
		buf1++;
		buf2++;
	}
}

 要改的三个点我们都解决了,整理一下升级后的代码吧

//自定义比较函数(int)
int compar_int(const void* e1,const void* e2)
{
	return *(int*)e1 - *(int*)e2;
}

//交换函数
void Swap(char* buf1, char* buf2, size_t width)
{
	for (int i = 0; i < width; i++)
	{
		char tmp = *buf1;
		*buf1 = *buf2;
		*buf2 = tmp;
		buf1++;
		buf2++;
	}
}

//冒泡排序函数
void bubble_sort(void* base, size_t sz, size_t width, int(*compar)(const void* e1, const void* e2))
{
	int i = 0;//趟数
	for (i = 0; i < sz - 1; i++)
	{
		int j = 0;
		for (j = 0; j < sz - i - 1; j++)
		{
			
			if(compar((char*)base+j*width, (char*)base + (j+1) * width)>0)
			{
				Swap((char*)base + j * width, (char*)base + (j + 1) * width, width);
			}
		}
	}
}

//test函数
void test()
{
	int arr[] = { 6,4,1,2,9,3,7,8,10,5 };
	int sz = sizeof(arr) / sizeof(arr[0]);

	bubble_sort(arr, sz, sizeof(arr[0]), compar_int);

	//打印
	for (int i = 0; i < sz; i++)
	{
		printf("%d ", arr[i]);
	}
}

int main()
{
	test();
	return 0;
}

//创建一个结构体
struct students
{
	char name[20];
	int age;
};

//比较函数(结构体name)
int compar_students_by_name(const void* e1, const void* e2)
{
	return strcmp((*(struct students*)e1).name,(*(struct students*)e2).name);
}

//自定义比较函数(int)
int compar_int(const void* e1,const void* e2)
{
	return *(int*)e1 - *(int*)e2;
}

//交换函数
void Swap(char* buf1, char* buf2, size_t width)
{
	for (int i = 0; i < width; i++)
	{
		char tmp = *buf1;
		*buf1 = *buf2;
		*buf2 = tmp;
		buf1++;
		buf2++;
	}
}

//冒泡排序函数
void bubble_sort(void* base, size_t sz, size_t width, int(*compar)(const void* e1, const void* e2))
{
	int i = 0;//趟数
	for (i = 0; i < sz - 1; i++)
	{
		int j = 0;
		for (j = 0; j < sz - i - 1; j++)
		{
			
			if(compar((char*)base+j*width, (char*)base + (j+1) * width)>0)
			{
				Swap((char*)base + j * width, (char*)base + (j + 1) * width, width);
			}
		}
	}
}

//test函数
void test()
{
	struct students classA[3] = { {"jason",18},{"jack",28},{"leon",33} };
	int sz = sizeof(classA) / sizeof(classA[0]);

	bubble_sort(classA, sz, sizeof(classA[0]), compar_students_by_name);

	//打印
	for (int i = 0; i < sz; i++)
	{
		printf("%s %d ", classA[i].name,classA[i].age);
	}
}

int main()
{
	test();
	return 0;
}

这样我们的代码也就写完了,通过这一次的改写冒泡排序,我们是不是能感受到void*指针的遍历,这种编程叫做泛型编程。

大家可以在自行梳理一下,有帮助请给一个三连吧! 

### C语言常见库函数的模拟实现 以下是几个常见的C语言库函数及其模拟实现的方法和解析: #### 1. `strstr` 函数的模拟实现 `strstr` 是一个用于查找子串位置的标准库函数。其功能是在目标字符串中寻找指定的子串,并返回指向第一次匹配处的指针。 ```c #include <stdio.h> #include <string.h> char* my_strstr(const char* haystack, const char* needle) { if (needle[0] == '\0') return (char*)haystack; while (*haystack != '\0') { const char *h = haystack, *n = needle; while (*h == *n && *n != '\0') { h++; n++; } if (*n == '\0') return (char*)haystack; haystack++; } return NULL; } ``` 上述代码实现了 `strstr` 的核心逻辑,逐字符对比两个字符串并判断是否存在完全匹配的情况[^2]。 --- #### 2. `strlen` 函数的模拟实现 `strlen` 是用来计算字符串长度的一个常用库函数。其实现可以通过遍历字符串直到遇到 `\0` 来完成计数操作。 ```c #include <assert.h> size_t my_strlen(const char* str) { assert(str != NULL); size_t count = 0; while (*str++ != '\0') { count++; } return count; } ``` 此版本基于循环逐一读取字符的方式统计字符串长度[^3]。 --- #### 3. `strcpy` 函数的模拟实现 `strcpy` 将源字符串复制到目标缓冲区中。需要注意的是,在实际应用时要确保目标缓冲区有足够的空间来存储完整的字符串副本。 ```c #include <stdlib.h> char* my_strcpy(char* dest, const char* src) { char* ret = dest; while ((*dest++ = *src++) != '\0'); return ret; } ``` 该实现在每次迭代过程中将单个字符从源地址拷贝至目的地址直至结束符为止[^1]。 --- #### 4. `strcmp` 函数的模拟实现 `strcmp` 对比两字符串的内容差异,如果相等则返回值为零;否则依据字典序给出正负数值表示前者大于后者还是小于后者的关系。 ```c int my_strcmp(const char* s1, const char* s2){ while(*s1 && (*s1==*s2)){ ++s1; ++s2; } return *(unsigned char *)s1 - *(unsigned char *)s2 ; } ``` 这段代码展示了如何利用简单的条件语句配合递增运算符达成预期效果。 --- #### 5. `qsort` 排序算法自定义比较器 虽然严格意义上讲这不是单一某个特定“库函数”的重写形式,但是提供定制化行为的能力对于学习理解底层机制非常重要。下面是一个整型数组升序排列的例子: ```c void qsort_example() { int array[] = {78, 90, 67, 89}; int length = sizeof(array)/sizeof(int); qsort(array, length, sizeof(int), cmp_int); for(int i=0;i<length;i++) printf("%d ",array[i]); } // 定义比较函数 int cmp_int(const void* a, const void* b){ return (*(int*)a - *(int*)b); } ``` 这里展示了一个典型的调用场景以及相应的辅助工具——即所谓的回调接口设计模式[^4]。 --- ### 总结 以上列举了几种典型情况下针对不同需求所采取的不同策略和技术手段来进行相应标准库组件的手动构建过程。每一种都有各自的特点与适用范围,请根据具体项目背景灵活选用最合适的方案加以实践验证优化改进!
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值