您的位置:首页 > 其它

快速排序与折半查找算法函数:qsort与bsearch

2013-04-21 11:41 281 查看
qsort用来排序,bsearch用二分法来查找元素

void qsort( void *base, size_t num, size_t width,int (__cdecl *compare)(const void *elem1, const void *elem2 ) );

base: 要排序的数组

num: 数组中的元素数目

width: 每个数组元素占用内存空间,可使用sizeof获得

compare: 比较两个数组元素的比较函数。本比较函数的第一个参数值小于、等于、大于第二参数值时,本比较函数的返回值应分别小于、等于、大于零。compare的两个参数elem1、elem2大小均等于width.

void *bsearch( const void *key, const void *base, size_t
num,size_t width, int ( __cdecl *compare) ( const void *elem1, const void *elem2 ) );

qsort函数的compare参数也是一个函数指针,但其所指函数的参数elem1指向key,只有参数elem2大小等于width.

key:待查找的元素,它的类型不确定

base:升序排列的数组

num、width:同qsort函数的参数

compare:与qsort中不同之处在于它的参数elem1指向key,参数elem2大小等于width,指向base中的元素。

/////////////////////////////////
#include <stdlib.h>
typedef struct {
int no;
char name[100];
}student;

int compare(const void *s0, const void *s1); /* Declare a function for compare */
int find(const void *s0, const void *s1);

student yy[] = {{1, "aaa"}, {2, "bbb"}, {5, "agd"}, {0, "xxx"}};
void main( )
{
student *argv = yy;
int argc = sizeof(yy) / sizeof(yy[0]);

student *result;
int key = 2;
int i;

/* Sort using Quicksort algorithm: */
qsort(argv, (size_t)argc, sizeof(student), compare );

for( i = 0; i < argc; ++i )    /* Output sorted list */
printf( "{%d %s} ", argv[i].no, argv[i].name);

/* Find the word "key" using a binary search algorithm: */
result = (student *)bsearch(&key, argv, argc, sizeof(student), find );
if( result )
printf( "\n{%d %s} found at %Fp\n", result->no, result->name, result);
else
printf( "\nkey not found!\n" );
}

int compare(const void *s0, const void *s1)
{
student *a0 = (student *)s0;
student *a1 = (student *)s1;

if (a0->no == a1->no)
return 0;
else if (a0->no > a1->no)
return 1;
else
return -1;
}

int find(const void *s0, const void *s1)
{
int no = *(int*)s0;
student *s = (student*)s1;

if (no == s->no)
return 0;
else if (no > s->no)
return 1;
else
return -1;
}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: