c语言回调函数 -----qsort

版权声明:[email protected] https://blog.csdn.net/qq_271334644/article/details/84815143

       回调函数就是一个通过函数指针调用的函数。如果你把函数的指针(地址)作为参数传递给另一个函数,当这个指针被用来调用其所指向的函数时,我们就说这是回调函数。回调函数不是由该函数的实现方直接调用,而是在特定的事件或条件发生时由另外的一方调用的,用于对该事件或条件进行响应。

下面我们给出一个练习

                                                qsort()实现基于快速排序

#include<stdio.h>
#include<stdlib.h>
//CmpInt是qsort的比较函数.CmpInt调用时机不是由程序员自己决定
//而是由qsort内部来决定的.像这种风格的函数,就叫做回调函数
int  CmpInt(void* p1,void* p2) {
	int* a = (int*) p1;
	int* b = (int* )p2;
	//如果*a<*b相当于让函数返回真
	//如果期望p2指向的元素在p1的前面返回真
	//如果期望p1指向的元素在p2的前面返回假
	return  *a < *b;
}
int main() {
	int  arr[] = { 9,5,2,7 };
	//在C++中会有更好的选择
	//std::sort运行效率比qsort更好
	qsort(arr,sizeof(arr)/sizeof(arr[0]),sizeof(arr[0]),CmpInt);
	for (int i = 0; i < 4; ++i) {
		printf(" %d", arr[i]);
	}
	system("pause");
	return 0;
}

qsort采用冒泡排序的一个例子


#include <stdio.h>
int int_cmp(const void * p1, const void * 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 *))

{
    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[] = { 1, 3, 5, 7, 9, 2, 4, 6, 8, 0 };
    //char *arr[] = {"aaaa","dddd","cccc","bbbb"};
    int i = 0;
    bubble(arr, sizeof(arr) / sizeof(arr[0]), sizeof (int), int_cmp);
    for (i = 0; i< sizeof(arr) / sizeof(arr[0]); i++)
   {
       printf( "%d ", arr[i]);
   }
    printf("\n");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_271334644/article/details/84815143