*****************************************************************baidu baike*************************************************************************
用 法: void qsort(void *base, int nelem, int width, int (*fcmp)(const void *,const void *));
1
2
3
4
|
intcomp(constvoid*a,constvoid*b)
{
return
*(
int
*)a-*(
int
*)b;
}
|
1
2
3
4
5
6
7
8
9
10
11
12
|
qsort
(a,1000,
sizeof
(
int
)*2,comp);
intcomp(constvoid*a,constvoid*b)
{
return
((
int
*)a)[0]-((
int
*)b)[0];
}
|
#include <stdio.h> #include <stdlib.h> #include <time.h> #define LEN 5 void arr_init(int num[], int len) { int i; srand(time(NULL)); for(i = 0; i < len; i++){ num[i] = rand()%50; } } void arr_print(int num[], int len) { int i; for(i = 0; i < len; i++){ printf("%d ", num[i]); } printf("\n"); } int cmp_int(const void *a, const void *b) { return *(int *)a - *(int *)b; } int main(void) { int num[LEN]; int fd; int *find_num; arr_init(num, LEN); arr_print(num, LEN); qsort(num, LEN, sizeof(int), cmp_int); arr_print(num, LEN); printf("enter search num:\n"); scanf("%d", &fd); find_num = (int *)bsearch(&fd, num, LEN, sizeof(int), cmp_int); (find_num == NULL) ? printf("no find\n") : printf("find the num %d\n", fd); return 0; } /* akaedu@akaedu-G41MT-D3:~/lin/804_sf$ ./4 27 38 2 23 3 2 3 23 27 38 enter search num: 3 find the num 3 akaedu@akaedu-G41MT-D3:~/lin/804_sf$ ./4 0 5 48 17 19 0 5 17 19 48 enter search num: 66 no find akaedu@akaedu-G41MT-D3:~/lin/804_sf$ */