函数指针在通用排序算法实现中的使用 (2006-7-29)


指针是C语言初学者最为头疼的,然而,如果学好、用好了指针,你的程序功底就又增强了N级……

在Programing时,经常需要进行排序,如果自己写,通用性不好,也浪费时间和精力,有句话说得好:写程序就是为了不(少)写程序。其实在C标准库里已经有一个可用于 所有情况的快速排序的实现函数了,我们要做的只是写一个比较函数,这里就要用到函数指针了,下面详细说明:

C标准库中快速排序函数的声明:
cpp 代码
  1. #include <stdlib.h></stdlib.h>  
  2.   
  3. void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *));   
  4.   
  5. /* 对base[0], base[1], .... , base[nmemb - 1] 这nmemb个大小为size的元素,根据compar所指向的函数所定义的比较方式进行排序。   
  6. */  

在Linux的帮助页中是这样描述的:

DESCRIPTION
        The qsort() function sorts an  array with nmemb elements of  size size. The base argument points to the start of the array.

        The contents of the array are sorted in ascending order according to a comparison function pointed to by compar, which is called with two arguments that point to the objects being compared.

        The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. If two members compare as equal, their order in the sorted array is undefined.

RETURN VALUE
        The qsort() function returns no value.


在声明void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *));中的compar是一个函数指针,它指向一个带两个void *型参数且返回值为int的函数。base是要进行排序的数组的首地址;nmemb是要进行排序的元素的个数;size是数组中一个元素的大小(占用内存的字节数);compar是指向一个比较函数的函数指针。通俗地说就是对base[0], base[1], base[2], ...., base[nmemb-1]进行排序。

用法说明示例程序:

cpp 代码
  1. #include <stdio.h></stdio.h> 
  2. #include <stdlib.h></stdlib.h>
  3.   
  4. /* 比较两个指针*p1 和 *p2所指向的字符  
  5.    输入参数:p1: 要比较的第一个字符的指针;  
  6.              p2: 要比较的第二个字符的指针.  
  7.    返回值:如果第一个字符*p1的ASCII码小于第二个字符*p2的ASSCII码,返回-1;  
  8.           若等于,返回0;若大于,返回1。  
  9. */  
  10. int cmpchar(const void *ch1, const void*ch2)   
  11. {   
  12.     char* ch1 = (char*)p1;   
  13.     char* ch2 = (char*)p2;   
  14.   
  15.     if (*ch1 - *ch2 > 0)   
  16.         return 1;   
  17.     else if (*ch1 - *ch2 == 0)   
  18.         return 0;   
  19.     else  
  20.         return -1;   
  21. }   
  22.   
  23. int main(void)   
  24. {   
  25.     char str[7] = "efdcba";   
  26.   
  27.     qsort(str, 6, sizeof(char), cmpchar);   
  28.     printf("%s\n", str);   
  29.     return 0;   
  30. }   

关于函数指针的具体定义和用法请看 The C Programming Language (K & R) 第118-121页 *_*
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值