<a target=_blank id="cb_post_title_url" class="singleposttitle" href="http://www.cnblogs.com/BeyondAnyTime/archive/2012/05/22/2513776.html">qsort和sort学习与比较</a>
http://www.cnblogs.com/BeyondAnyTime/archive/2012/05/22/2513776.html
/*bseach用法:
void *bsearch(const void *key, const void *base, size_t nelem, size_t width, int(*fcmp)(const void *, const *));
参数:key指向所要查找的元素.第一个找的关键字。第二个:要查找的数组。第三个:指定数组中元素的数目。
第四个:每个元素的长度(以字符为单位)。第五个:指向比较函数的指针.
*/
/*qsort用法:
void qsort(void *base, int nelem, int width, int (*fcmp)(const void *,const void *));
其中base是排的序一个集合数组,num是这个数组元素的个数,width是一个元素的大小,comp是一个比较函数。
*/
#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
int cmp_int(const void *a, const void *b)
{
return *(int *)a - *(int *)b;
}
// char
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 = 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$
*/
qsort bseach 简单使用
最新推荐文章于 2021-03-10 03:08:03 发布