回调函数---通用数组排序案例

2021-03-04 10:36:14 浏览数 (1)

内置数据类型:

代码语言:javascript复制
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
//自定指定排序规则
int sortWay(void* v1, void* v2)
{
	double* a = (double*)v1;
	double* b = (double*)v2;
	//如果第一个参数大于第二个参数就代表是p[maxOrMin]>p[j],升序排列
	return (*a > *b);
}
//通用数组排序
void Sort(void* arr, int size, int len, int(*sort)(void*, void*))
{
	char* p = (char*)arr;

	char* temp = (char*)malloc(size);
	for (int i = 0; i < len; i  )
	{
		int maxOrMin = i;
		char* pi = p   size * i;
		char* pMaxOrMin = p   size * i;
		for (int j = i   1; j < len; j  )
		{
			//获取数组中每个元素的首地址
			char* pj = p   size * j;
			if (sortWay(pi, pj))
			{
				maxOrMin = j;
				pi = pj;
			}
		}
		if (maxOrMin != i)
		{
			//内存拷贝,防止直接赋值出现乱码的问题
			memcpy(temp, pMaxOrMin, size);
			memcpy(pMaxOrMin, pi, size);
			memcpy(pi, temp, size);
		}
	}
	if (temp != NULL)
	{
		free(temp);
		temp = NULL;
	}
}
void test()
{
	double arr[5] = { 1.77,4.24,2.98,5.78,3.14 };
	Sort(arr, sizeof(double), 5, sortWay);
	for (int i = 0; i < 5; i  )
	{
		printf("%.2lf ", arr[i]);
	}
}
int main()
{
	test();
	return 0;
}

自定义数据类型:

代码语言:javascript复制
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
//自定义数据类型
struct person {
	char name[32];
	int age;
};
//自定指定排序规则
int sortWay(void* v1, void* v2)
{
	person* p1 = (person*)v1;
	person* p2 = (person*)v2;
	//如果第一个参数小于第二个参数就代表是降序排列
	return ((p1->age) > (p2->age));
}
//通用数组排序
void Sort(void *arr,int size,int len,int(*sort)(void *,void*))
{
	
	char* p = (char*)arr;

	char* temp = (char*)malloc(size);
	for (int i = 0; i < len; i  )
	{
		int maxOrMin = i;
		char* pi = p   size * i;
		char* pMaxOrMin = p   size * i;
		for (int j = i   1; j < len; j  )
		{
			   //获取数组中每个元素的首地址
			char* pj = p   size * j;
			if (sortWay(pi, pj))
			{
				maxOrMin = j;
				pi = pj;
			}
		}
		if (maxOrMin != i)
		{
			 //内存拷贝,防止直接赋值出现乱码的问题
			memcpy(temp, pMaxOrMin, size);
			memcpy(pMaxOrMin, pi, size);
			memcpy(pi, temp, size);
		}
	}
	if (temp != NULL)
	{
		free(temp);
		temp = NULL;
	}
	
}
void test()
{
	person p[5] = {
		{"大忽悠",18},
		{"小朋友",17},
		{"大朋友",20},
		{"小忽悠",19},
		{"happy",100},
	};
	//按年龄降序
	Sort(p, sizeof(person), 5, sortWay);
	for (int i = 0; i < 5; i  )
	{
		printf("姓名:%st年龄:%dn", p[i].name, p[i].age);
	}
}
int main()
{
	test();
	return 0;
}

注意:

0 人点赞