库函数qsort使用示范
Posted asurudo
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了库函数qsort使用示范相关的知识,希望对你有一定的参考价值。
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 5 struct Struction 6 { 7 double one; 8 int another; 9 }; 10 11 int CmpInt_1(const void *a,const void *b) 12 { 13 return *(int*)a - *(int*)b; 14 } 15 16 int CmpInt_2(const void *a,const void *b) 17 { 18 int *c = (int *)a; 19 int *d = (int *)b; 20 21 if(*(c+0) != *(d+0)) 22 { 23 return *(c+0) - *(d+0); 24 } 25 else 26 { 27 return *(c+1) - *(d+1); 28 } 29 } 30 31 int CmpStruction(const void *a,const void *b) 32 { 33 struct Struction *c = (struct Struction *)a; 34 struct Struction *d = (struct Struction *)b; 35 36 if(c->one != d->one) 37 { 38 return c->one > d-> one ? 1 : 0; 39 } 40 else 41 { 42 return c->another > d-> another ? 1 : 0; 43 } 44 } 45 46 int CmpString(const void *a,const void *b) 47 { 48 return strcmp((char*)a,(char*)b); 49 } 50 51 int main() 52 { 53 int i,j; 54 55 //sort int* 56 int TestArray_1[10] = {718,224,3332,4443,55,31,66,79,90,7}; 57 qsort(TestArray_1,10,sizeof(int),CmpInt_1); 58 59 for(i = 0; i < 10; i ++) 60 { 61 printf("%d ",TestArray_1[i]); 62 } 63 printf(" "); 64 65 66 //sort int** 67 int TestArray_2[5][2] = {{0,1},{2,7},{-4,99},{1,900},{2,423}}; 68 qsort(TestArray_2,5,sizeof(TestArray_2[0]),CmpInt_2); 69 70 for(i = 0; i < 5; i ++) 71 { 72 for(j = 0; j < 2; j ++) 73 { 74 printf("%d ",TestArray_2[i][j]); 75 } 76 printf(" "); 77 } 78 printf(" "); 79 80 //sort struct with two variable 81 struct Struction *TestArray_3 = malloc(5*sizeof(struct Struction)); 82 TestArray_3[0].one = 1.1; 83 TestArray_3[0].another = 18; 84 TestArray_3[1].one = 43; 85 TestArray_3[1].another = -99; 86 TestArray_3[2].one = 1.1; 87 TestArray_3[2].another = 900; 88 TestArray_3[3].one = 3; 89 TestArray_3[3].another = 6; 90 TestArray_3[4].one = 2; 91 TestArray_3[4].another = 4; 92 93 qsort(TestArray_3,5,sizeof(struct Struction),CmpStruction); 94 for(i = 0; i < 5; i ++) 95 { 96 printf("%lf %d ",TestArray_3[i].one,TestArray_3[i].another); 97 } 98 printf(" "); 99 100 //sort string 101 char TestArray_4[5][100]; 102 strcpy(TestArray_4[0],"Asurudo"); 103 strcpy(TestArray_4[1],"Lokianyu"); 104 strcpy(TestArray_4[2],"Hatsune"); 105 strcpy(TestArray_4[3],"Miku"); 106 strcpy(TestArray_4[4],"Aqours"); 107 108 qsort(TestArray_4,5,sizeof(TestArray_4[0]),CmpString); 109 for(i = 0;i < 5;i ++) 110 { 111 puts(TestArray_4[i]); 112 } 113 114 return 0; 115 }
以上是关于库函数qsort使用示范的主要内容,如果未能解决你的问题,请参考以下文章