qsort函数用法举例
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 //数字比较函数 5 int cmp_num(const void* a, const void* b) 6 { 7 return *(int*)a - *(int*)b; 8 } 9 10 //字符比较函数 11 int cmp_char(const void* a, const void* b) 12 { 13 return *(char*)a - *(char*)b; 14 } 15 16 //字符串比较函数 17 int cmp_string(const void* a, const void* b) 18 { 19 return strcmp((char*)a, (char*)b); 20 } 21 22 //结构体某个成员比较函数 23 struct Node 24 { 25 double data; 26 int other; 27 }; 28 int cmp_struct(const void* a, const void* b) 29 { 30 return (*(struct Node*)a).data > (*(struct Node*)b).data ? 1 : -1; 31 } 32 33 int main() 34 { 35 int i; 36 //1.对一维数组进行排序 37 int n, *array; 38 scanf("%d", &n); 39 array = (int*)malloc(n*sizeof(int)); 40 for(i = 0; i < n; i++) 41 { 42 scanf("%d", (array+i)); 43 } 44 qsort(array, n, sizeof(int), cmp_num); 45 for(i = 0; i < n; i++) 46 { 47 printf("%d ", array[i]); 48 } 49 free(array); 50 printf("\n\n"); 51 52 //2.对二维数组进行排序 53 int j; 54 int array2[5][2] = {{57, 68}, {59, 52}, {72, 28}, {96, 33}, {24, 42}}; 55 qsort(array2, 5, sizeof(int)*2, cmp_num); 56 for(i = 0; i < 5; i++) 57 { 58 for(j = 0; j < 2; j++) 59 { 60 printf("%d ", array2[i][j]); 61 } 62 printf("\n\n"); 63 } 64 65 //3.对字符进行排序 66 char array3[] = "cdefba"; 67 qsort(array3, strlen(array3), sizeof(char), cmp_char); //string.h 68 for(i = 0; i < (int)strlen(array3); i++) 69 { 70 printf("%c ", array3[i]); 71 } 72 printf("\n\n"); 73 74 //4.对字符串进行排序 75 char array4[5][10] = {"this", "is", "my", "computer", "."}; 76 qsort(array4, 5, sizeof(array4[0]), cmp_string); 77 for(i = 0; i < 5; i++) 78 { 79 printf("%s\n", array4[i]); 80 } 81 printf("\n"); 82 83 //5.对结构体某个成员进行排序 84 struct Node array5[5] = {{3, 2}, {1.2, 5}, {1.1, 5}, {8.1, 9}, {5.7, 6}}; 85 qsort(array5, 5, sizeof(array5[0]), cmp_struct); 86 for(i = 0; i < 5; i++) 87 { 88 printf("%f %d\n", array5[i].data, array5[i].other); 89 } 90 return 0; 91 }
说明:
compare比较函数原型:compare( (void *) & elem1, (void *) & elem2 );
Compare函数的返回值 |
描述
|
<0 | elem1将被排在elem2前面 |
0 | elem1 等于 elem2 |
>0 | elem1 将被排在elem2后面 |
亲爱的读者:如果觉得本文对你有所帮助,请点击推荐,分享给其他人!