20150124 【 Linux-C 函数指针 】 模拟快速排序程序--快排

来源:互联网 发布:jquery源码 on方法 编辑:程序博客网 时间:2024/04/29 09:12


快排的特点就是通用性;

只要你提供比较函数 cmp

它就能对任何类型的数据进行排序。



大一的时候很不解这玩意的原理,

现在总于知道了————>函数指针。。。



所以就手敲了一遍。


一个是标准的int数组排序,

另一个是结构体数组排序。


这里用宏定义控制。










#include <stdio.h>#include <stdlib.h>#include <string.h>#include <time.h>//#define USE_INT//定义 USE_INT 时,TYPE_T 改为 int#define TYPE_Tpeople#define LEN_MAX10100const char alpha[] = "abcdefghijklnmopqrstuvwxyz";const int alphaLen = sizeof(alpha)-1;typedef struct _people{int age;char name[123];}people;void t_sort(TYPE_T *src, TYPE_T *aim, int n, int (*p)(const TYPE_T *x, const TYPE_T *y)){int i=0, j=0, flag=0;TYPE_T tmp;TYPE_T *maxx=NULL, *temp=NULL;for(i=0; i<n; i++){aim[i] = src[i];}for(i=0; i<n; i++){flag = i;for(j=i+1; j<n; j++){if( (*p)(aim+j, aim+flag) )flag = j;}tmp = aim[flag];aim[flag] = aim[i];aim[i] = tmp;}}TYPE_T src[LEN_MAX], aim[LEN_MAX];int t_cmp(const TYPE_T *a, const TYPE_T *b){#ifdef USE_INTreturn *a < *b;#elseif( a->age == b->age )return strcmp(a->name, b->name) < 0;return a->age < b->age;#endif}TYPE_T t_rand_num(void){TYPE_T res;int i=0, len=5;#ifdef USE_INTres = rand()%0xFFFF;#elseres.age = rand()%100+1;char ss[len+1];for(i=0; i<len; i++)res.name[i] = alpha[ rand()%alphaLen ];res.name[len] = '\0';#endifreturn res;}int main(int argc, char **argv){int i=0, n=0;srand( time(NULL) );//for( ; ; ){n = rand()%30 + 1;for(i=0; i<n; i++){src[i] = t_rand_num();}t_sort(src, aim, n, t_cmp);printf("一共 %d 个数:\n", n);for(i=0; i<n; i++){#ifdef USE_INTprintf("%d ", src[i]);#elseprintf("%3d %s\n", src[i].age, src[i].name);#endif}puts("-----------------------------"); for(i=0; i<n; i++){#ifdef USE_INTprintf("%d ", aim[i]);#elseprintf("%3d %s\n", aim[i].age, aim[i].name);#endif}puts("\n\n\n");//sleep( 1 ); }return 0;}


0 0
原创粉丝点击