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

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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值