使用qsort()和bsearch()进行快速排序和折半查找

使用<stdlib.h>提供的库函数qsort()和bsearch(),进行快速排序和折半查找。

同过对字符串的排序和查找,掌握对qsort()和bsearch()的使用。首先理解快速排序的算法,就是先设定关键字,以此为界进行划分,小的放前面,大的放后面,然后对着两拨进行同用的划分和排放,直至完成;折半查找就是先中间进行比较查找,再在符合的范围中间比较查找,直至完成。

使用这两个函数的需要注意的事项:函数参数的类型一定要匹配!

使用快速排序示例:

#include<stdio.h>
#include<stdlib.h>
int compare(const void *a,const void *b);
int main(void)
{
	//int num[4] = {3,4,1,2};
	char *str[3];
	str[0] = "bit";
	str[1] = "cout";
	str[2] = "about";//字符串赋值 
	int i;
	for(i = 0;i < 3; i++)
	{
		printf("%s\t",str[i]);	
	}
	printf("\n");
	qsort(str ,3 ,sizeof(str[0]) ,compare);//函数的指针 
	for(i = 0;i < 3; i++)
	{
		printf("%s\t",str[i]);	
	}
	printf("\n");
} 
int compare(const void *a,const void *b)
{
	return strcmp(*( char** )a ,*( char** )b);
}
使用折半查找的示例:

/*
**功能:使用折半法查找关键字,使用<stdlib.h>提供的bsearch()库函数进行查找
**函数:void* bsearch (const void*, const void*, int, int, int (*)(const void*, const void*)); 
**参数:匹配参数,数组,数组的长度,数组元素内存大小,比较函数 
**注释:只有先排序,才有查找 ,参数的类型要一致 
*/ 
#include<stdio.h>
#include<stdlib.h>
int compare(const void *a,const void *b);
int main(void)
{
	//int num[4] = {3,4,1,2};
	char **foundp = NULL;
	char *str[3];
	char *key = "about";
	str[0] = "bit";
	str[1] = "cout";
	str[2] = "about";//字符串赋值 
	int i;
	for(i = 0;i < 3; i++)
	{
		printf("%s\t",str[i]);	
	}
	printf("\n");
	qsort(str ,3 ,sizeof(str[0]) ,compare);//快速排序 
	for(i = 0;i < 3; i++)
	{
		printf("%s\t",str[i]);	
	}
	printf("\n");
	foundp = (char*)bsearch(&key,str,3,sizeof(str[0]),compare);//折半查找 ,&key和str的类型必须一致 
	if(foundp)
	printf("%s\n",*foundp);
	else
	printf("NOT FOUND!\n");
	
}
int compare(const void *a,const void *b)
{
	return strcmp(*( char** )a ,*( char** )b);
} 

充分利用好提供的库函数,能省不少事,“站在巨人的肩膀上才能看到更远”!

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值