函数指针的使用(整数排序)

函数指针的使用(整数排序)

  1 #include<stdio.h>
  2 #include<stdlib.h>
  3 #include<string.h>
  4 #include<time.h>
  5 
  6 //申请内存空间
  7 int *apply(int len);
  8 
  9 //释放数组内存空间
 10 void release(int *arr);
 11 
 12 //对某个内存地址进行输出操作
 13 void print(int *pval);
 14 
 15 //对某个内存地址进行初始化操作
 16 void init(int *pval);
 17 
 18 //将序比较,为真时返回1
 19 int desc(int *left, int *right);
 20 //升序比较
 21 int asc(int *left, int *right);
 22 
 23 //对数组起始、终止地址元素进行某种操作
 24 void foreach(int *beg, int *end, void (*operate)(int*));
 25 //对数组起始、终止地址元素进行排序
 26 void sort(int *beg, int *end, int (*cmp)(int *left, int *right));
 27 
 28 
 29 int main()
 30 {
 31     int len;
 32     int *arr;
 33 
 34     srand(time(NULL));//保证每次出现的随机数都不同
 35     len = rand() % 20 + 1;
 36     arr = apply(len);
 37     //初始化
 38     foreach(arr,arr+len-1,&init);
 39     //打印输出
 40     foreach(arr,arr+len-1,&print);
 41     printf("
");
 42 
 43     //升序
 44     printf("升序序列:
");
 45     sort(arr,arr+len-1,&asc);
 46     foreach(arr,arr+len-1,&print);
 47     printf("
");
 48 
 49     //降序
 50     printf("将序序列:
");
 51     sort(arr,arr+len-1,&desc);
 52     foreach(arr,arr+len-1,&print);
 53     printf("
");
 54 
 55     return 0;
 56 }
 57 
 58 
 59 int *apply(int len)
 60 {
 61     int *arr = (int*)calloc(len,sizeof(int));
 62     return arr;
 63 }
 64 
 65 void release(int *arr)
 66 {
 67     free(arr);
 68 }
 69 
 70 void print(int *pval)
 71 {
 72     printf("%4d",*pval);
 73 }
 74 
 75 void init(int *pval)
 76 {
 77     *pval = rand() % 100;
 78 }
 79 
 80 int desc(int *left, int *right)
 81 {
 82     if(*left >= *right)
 83         return 1;
 84     return 0;
 85 }
 86 
 87 int asc(int *left, int *right)
 88 {
 89     if(*left <= *right)
 90         return 1;
 91     return 0;
 92 }
 93 //对起始、终止地址元素进行某种操作
 94 void foreach(int *beg, int *end, void (*operate)(int*))
 95 {
 96     while(beg <= end)
 97     {
 98         (*operate)(beg);
 99         beg++;
100     }
101 }
102 
103 //快速排序
104 void sort(int *beg, int *end, int (*cmp)(int *left, int *right))
105 {
106     //暂存起始、终止地址
107     int *start = beg;
108     int *rear = end;
109     int pivot = *beg;//第一个元素为支点
110 
111     while(beg < end)
112     {
113         while(beg < end && (*cmp)(&pivot,end))
114             end--;
115         *beg = *end;
116 
117         while(beg < end && (*cmp)(beg,&pivot))
118             beg++;
119         *end = *beg;
120         //将支点放到最终位置
121         *beg = pivot;
122     }
123     if(start != beg)
124         sort(start,beg-1,(*cmp));
125     if(rear != end)
126         sort(beg+1,rear,(*cmp));
127 }

 运行结果:

原文地址:https://www.cnblogs.com/cpsmile/p/4425836.html