C语言:利用函数回调实现:冒泡排序各类型的通用排序。

#include<stdio.h>
#include<string.h>


void swap(char* buf1, char* buf2,int width)
{
    
    
	for (int i = 0; i < width; i++)
	{
    
    
		char tmp = *buf1;
		*buf1 = *buf2;
		*buf2 = tmp;
		buf1++;
		buf2++;
	}
}
void bubblesort(void* base, int sz, int width, int (*cmp)(const void* e1, const void* e2))
{
    
    
	for (int i = 0; i < sz-1; i++)
	{
    
    
		for (int j = 0; j < sz - 1 - i; 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 cmp_int(const void* e1, const void* e2)
{
    
    
	return *(int*)e1 - *(int*)e2;
}
void test4()
{
    
    
	int arr[10] = {
    
     1,2,3,4,5,6,7,8,9,0 };
	int sz = sizeof(arr) / sizeof(arr[0]);
	bubblesort(arr, sz, sizeof(arr[0]), cmp_int);
	for (int i = 0; i < sz; i++)
	{
    
    
		printf("%d ", arr[i]);
	}
	printf("\n");
}

//----------------------------------------------------------------------
struct st
{
    
    
	char arr[20];
	int age;
};
int cmp_string(const void* e1, const void* e2)
{
    
    
	//void* 可以接收任意类型的地址;
	//void* 不可以进行解引用操作;
	//void* p 不可以进行++--操作。
	return strcmp(((struct st*)e1)->arr, ((struct st*)e2)->arr);
	//负值:e1<e2;
	//0:e1=e2;
	//正值:e1>e2。
}
void test5()
{
    
    
	struct st s[3] = {
    
     {
    
    "zhangsan",40},{
    
    "lisi",20},{
    
    "wangwu",30} };
	int sz = sizeof(s) / sizeof(s[0]);
	bubblesort(s, sz, sizeof(s[0]), cmp_string);
	for (int i = 0; i < sz; i++)
	{
    
    
		printf("%s ", s[i].arr);
	}
}



//----------------------------------------------------------------------
int main()
{
    
    
	test4();
	test5();
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_45275802/article/details/112972773