博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Linux C/C++编程一站式学习中折半查找(如果待查找的元素在数组中有多个则返回第一个)
阅读量:4302 次
发布时间:2019-05-27

本文共 829 字,大约阅读时间需要 2 分钟。

Linux C/C++编程一站式学习中折半查找(如果待查找的元素在数组中有多个则返回第一个)

折半查找

本节的折半查找算法有一个特点:如果待查找的元素在数组中有多个则返回其中任意一个,以本节定义的数组 int a[8] = { 1, 2, 2, 2, 5, 6, 8, 9 }; 为例,如果调用 binarysearch(2) 则返回3,即 a[3] ,而有些场合下要求这样的查找返回 a[1] (如果待查找的元素在数组中有多个则返回第一个)。请修改折半查找算法实现这一特性。

代码

#include 
#define LEN 8int a[LEN] = { 1, 2, 2, 5, 5, 6, 8, 9 };int binarysearch(int number){ int mid,start = 0,end = LEN - 1; while(start <= end){ mid = (start + end) / 2;// printf("%d\n", mid); if(a[mid] < number) start = mid + 1; else if(a[mid] > number) end = mid - 1; else //printf("%d\n", mid); for(int j=mid-1;j >= 0;j--) if(a[j] == a[mid]) mid = j; return mid; } return -1;}int main(void){ printf("%d\n", binarysearch(5)); return 0;}

结果截图]![(https://img-blog.csdn.net/20180109212507832?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdTAxMTU2MjEyMw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)

你可能感兴趣的文章
在eclipse上用tomcat部署项目404解决方案
查看>>
web.xml 配置中classpath: 与classpath*:的区别
查看>>
suse如何修改ssh端口为2222?
查看>>
详细理解“>/dev/null 2>&1”
查看>>
suse如何创建定时任务?
查看>>
suse搭建ftp服务器方法
查看>>
centos虚拟机设置共享文件夹并通过我的电脑访问[增加smbd端口修改]
查看>>
文件拷贝(IFileOperation::CopyItem)
查看>>
MapReduce的 Speculative Execution机制
查看>>
大数据学习之路------借助HDP SANDBOX开始学习
查看>>
Hadoop基础学习:基于Hortonworks HDP
查看>>
为什么linux安装程序 都要放到/usr/local目录下
查看>>
Hive安装前扫盲之Derby和Metastore
查看>>
永久修改PATH环境变量的几种办法
查看>>
大数据学习之HDP SANDBOX开始学习
查看>>
Hive Beeline使用
查看>>
Centos6安装图形界面(hdp不需要,hdp直接从github上下载数据即可)
查看>>
CentOS7 中把yum源更换成163源
查看>>
关于yum Error: Cannot retrieve repository metadata (repomd.xml) for repository:xxxxxx.
查看>>
linux下载github中的文件
查看>>