回调函数,qsort函数,与qsort函数的模拟

回调函数是指通过函数指针调用的函数,常用于在特定事件发生时进行响应。本文以C语言的qsort函数为例,解释了如何使用函数指针作为参数。qsort用于对指定大小和宽度的数组进行快速排序,其核心是一个用户提供的比较函数compare,该函数用于比较两个元素并决定排序关系。此外,还提到了模拟实现qsort函数的一种方法——冒泡排序算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

回调函数:

回调函数就是一个通过函数指针调用的函数,如果你把函数的指针作为参数传递给另一个函数,当这个指针被用来调用其所指向的函数时,我们就说这个函数为回调函数,

回调函数不是由该函数的实现方法直接调用,而是在特定的事件或者条件时由另外的一方调用,用于对该事件或者条件响应。

简单的说,就是一个函数的参数里面有一个函数指针参数,而这个函数指针对应的函数要自己用函数实现。很通俗,具体用途,我们来通过qsort函数来看看

void qsort( void *base, size_t num, size_t width, int (__cdecl *compare )(const void *elem1, const void *elem2 ) );

qsort函数原型和参数。

int (__cdecl *compare )(const void *elem1, const void *elem2 ) 这个就是函数指针做qsort函数是的参数

那么我们来模拟实现一下qsort函数,用冒泡法。

//实现qsort函数,用冒泡法;
#include<stdio.h>
#include<stdlib.h>
int int_cmp(const void *p1,const void *p2)//回掉函数,这一部分需要自己去实现
{

	return (strcmp(*(int *)p1,*(int *)p2));//处理字符串
        //return (*(int *)p1 > *(int *)p2);//处理整数
}
void swap(void *p1,void *p2,int size)
{
	int i = 0;
	for(i = 0; i<size; i++)
	{
		char tmp = *((char *)p1+i);
		*((char *)p1+i)=*((char *)p2+i);
		*((char *)p2+i)=tmp;
	}
}

void bubble(void *base,int count,int size,int(*cmp)(void *,void *))//用冒泡来实现qsort排序
{
	int i = 0;
	int j = 0;
	for(i=0;i<count-1;i++)
	{
		for(j=0;j<count-i-1;j++)
		{
			if(cmp((char *)base + j*size,(char *)base + (j+1)*size)>0)
			{
				swap((char *)base+j*size,(char *)base+(j+1)*size,size);
			}
		}

	}
}
int main()
{
        //int arr[] = {5,4,3,2,1,8,6,4};
		char *arr[] = {"aaa","ddd","ccc","bbb"};
        int i = 0;
        qsort(arr,sizeof(arr)/sizeof(arr[0]),sizeof(int),int_cmp);
        for(i=0; i<sizeof(arr)/sizeof(arr[0]);i++)
        {   
                printf("%s",arr[i]);
        }   
        printf("\n");
        return 0;
}

实现起来很简单,就是回调函数概念不太好理解。

The qsort function implements a quick-sort algorithm to sort an array of num elements, each of width bytes. The argument base is a pointer to the base of the array to be sorted. qsort overwrites this array with the sorted elements. The argument compare is a pointer to a user-supplied routine that compares two array elements and returns a value specifying their relationship. qsort calls the compare routine one or more times during the sort, passing pointers to two array elements on each call:

这是qsort函数的用法。对任意类型进行排序。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值