1 #include <stdio.h>
 2  
 3 //{3,5,8,7,6}
 4 /*
 5 int max(int *nums,int len)
 6 {
 7     int i;
 8     int max=nums[0];//假定第0个元素为最大值
 9     for(i=1;i<len;i++)
10     {
11         int value = *nums;
12         if(value>max)
13         {
14             max = value;//如果找到比max还大的,则max让位
15         }
16         nums++;
17     }
18     return max;
19 }
20 */
21  
22 typedef struct _Dog
23 {
24     char* name;
25     int age;
26 } Dog;
27 typedef int (*compareFunc)(void * data1,void * data2);
28 //data 待比较数据数组的首地址,uniteSize单元字节个数
29 //size:数据的长度。{1,3,5,6}:size=4
30 //比较data1和data2指向的数据做比较,
31 //如果data1>data2,则返回正数
32 void* max(void* data,int unitSize,int size,
33     compareFunc func)
34 {
35     int i;
36     char *ptr = (char *)data;
37     char *max = ptr;//假定最开始的元素为最大值
38     for(i=1;i<size;i++)
39     {      
40         char* item = ptr+i*unitSize;//计算第i个元素的首地址   
41         if(func(item,max)>0)//如果item大于max
42         //到底取几个字节进行比较是func内部的事情
43         {
44             max = item;
45         }
46     }
47     return max;//最大值的首地址
48 }
49  
50 //data1是第一个被比较数字的首地址
51 int intCompare(void* data1,void *data2)
52 {
53     int* ptr1 = (int*)data1;
54     int* ptr2 = (int*)data2;
55     int i1=*ptr1;
56     int i2=*ptr2;
57     return i1-i2;
58 }
59  
60 int dogCompare(void* data1,void* data2)
61 {
62     Dog* dog1 = (Dog*)data1;
63     Dog* dog2 = (Dog*)data2;
64     return (dog1->age)-(dog2->age);
65     //return (dog2->age)-(dog1->age);
66 }
67  
68 int main(int argc, char *argv[])
69 {
70     /*
71     int nums[] = {3,5,8,7,6};
72     int *pMax = (int *)max(nums,sizeof(int),sizeof(nums)/sizeof(int),
73         intCompare);
74     int max = *pMax;
75     printf("%d\n",max);
76     */
77     /*Dog dogs[] ={{"沙皮",3},{"腊肠",10},{"哈士奇",5},{"京巴",8},{"大狗",2}};*/
78     /*Dog *pDog = (Dog *)max(dogs,sizeof(Dog),
79         sizeof(dogs)/sizeof(Dog),dogCompare);
80     printf("%s=%d",pDog->name,pDog->age);*/
81     /*qsort(dogs,sizeof(dogs)/sizeof(Dog),sizeof(Dog),dogCompare);
82     int i;
83     for(i=0;i<sizeof(dogs)/sizeof(Dog);i++)
84     {
85         Dog dog = dogs[i];
86         printf("%s=%d|",dog.name,dog.age);
87     }*/
88     int nums[] = {3,5,8,7,6};
89     qsort(nums,sizeof(nums)/sizeof(int),sizeof(int),
90         intCompare);
91     int i;
92     for(i=0;i<sizeof(nums)/sizeof(int);i++)
93     {
94         int n = nums[i];
95         printf("%d|",n);
96     }
97  
98     return 0;
99 }

 

版权声明:本文为sening原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/sening/p/4521874.html