1 // To Compile and Run: g++ binary_search.cc -std=c++11 -Wall -O3 && ./a.out 8
2
3
4 #include <stdlib.h>
5 #include <assert.h>
6
7 #include <iostream>
8 #include <vector>
9
10
11 int BinarySearch(const std::vector<int> &inArr, int target) {
12 int left = 0;
13 int right = inArr.size() - 1;
14
15 while (true) {
16 if (left > right) {
17 std::cout << "Failed to find: " << target << "\n";
18 return -1;
19 }
20
21 int mid = left + (right - left) / 2;
22 if (target == inArr[mid]) {
23 return mid;
24 }
25
26 if (target > inArr[mid]) {
27 right = mid - 1;
28 }
29 // target < inArr[mid]
30 else {
31 left = mid + 1;
32 }
33 }
34
35 std::cerr << "Could never reach here.\n";
36 return -1;
37 }
38
39 int main(int argc, char const *argv[]) {
40 const std::vector<int> arr {
41 8, 7, 4, 3, -5, -9
42 };
43 assert(argc >= 2);
44 int target = atoi(argv[1]);
45
46 int indexOfTarget = BinarySearch(arr, target);
47 if (indexOfTarget < 0) {
48 std::cout << "Failed to find: " << target << "\n";
49 return -1;
50 }
51 std::cout << "Find: " << target << " in " << indexOfTarget << "\n";
52
53 return 0;
54 }

对于顺序排列的数组,只修改26行的符号就行了。

使用递归实现,只需要在BinarySearch函数中去掉while循环,判断结束后,return自身就行了。

代码如下:

 1 // To Compile and Run: g++ binary_search.cc -std=c++11 -Wall -O3 && ./a.out 8
2
3
4 #include <stdlib.h>
5 #include <assert.h>
6
7 #include <iostream>
8 #include <vector>
9
10
11 int BinarySearchRecursive(const std::vector<int> &inArr, int target, int left, int right) {
12 if (left > right) {
13 std::cout << "Failed to find: " << target << "\n";
14 return -1;
15 }
16
17 int mid = left + (right - left) / 2;
18 if (target == inArr[mid]) {
19 return mid;
20 }
21
22 if (target > inArr[mid]) {
23 right = mid - 1;
24 }
25 else {
26 left = mid + 1;
27 }
28
29 return BinarySearchRecursive(inArr, target, left, right);
30 }
31
32 int main(int argc, char const *argv[]) {
33 const std::vector<int> arr {
34 8, 7, 4, 3, -5, -9
35 };
36 assert(argc >= 2);
37 int target = atoi(argv[1]);
38
39 int indexOfTarget = BinarySearchRecursive(arr, target, 0, arr.size() - 1);
40 if (indexOfTarget < 0) {
41 std::cout << "Failed to find: " << target << "\n";
42 return -1;
43 }
44 std::cout << "Find: " << target << " in " << indexOfTarget << "\n";
45
46 return 0;
47 }

BinarySearch,逆序排列的数组的二分查找(折半查找),C++非递归+递归实现的更多相关文章

  1. Java数组逆序排列

    //逆序排列原理 /* A: 数组逆序原理* a: 题目分析* 通过观察发现,本题目要实现原数组元素倒序存放操作.即原数组存储元素为{12,69,852,25,89,588},逆序后为原数组存储元素变 ...

  2. Java实现蓝桥杯VIP算法训练 数组逆序排列

    试题 算法训练 数组逆序排列 资源限制 时间限制:1.0s 内存限制:256.0MB 问题描述 编写一个程序,读入一组整数(不超过20个),并把它们保存在一个整型数组中.当用户输入0时,表示输入结束. ...

  3. C语言 · 逆序排列

    算法提高 逆序排列   时间限制:1.0s   内存限制:512.0MB      问题描述 编写一个程序,读入一组整数(不超过20个),并把它们保存在一个整型数组中.当用户输入0时,表示输入结束.然 ...

  4. 算法笔记_158:算法提高 逆序排列(Java)

    目录 1 问题描述 2 解决方案 1 问题描述 问题描述 编写一个程序,读入一组整数(不超过20个),并把它们保存在一个整型数组中.当用户输入0时,表示输入结束.然后程序将把这个数组中的值按逆序重新存 ...

  5. 51nod 1020 逆序排列 DP

    在一个排列中,如果一对数的前后位置与大小顺序相反,即前面的数大于后面的数,那么它们就称为一个逆序.一个排列中逆序的总数就称为这个排列的逆序数. 如2 4 3 1中,2 1,4 3,4 1,3 1是逆序 ...

  6. SQL-27 给出每个员工每年薪水涨幅超过5000的员工编号emp_no、薪水变更开始日期from_date以及薪水涨幅值salary_growth,并按照salary_growth逆序排列。 提示:在sqlite中获取datetime时间对应的年份函数为strftime('%Y', to_date)

    题目描述 给出每个员工每年薪水涨幅超过5000的员工编号emp_no.薪水变更开始日期from_date以及薪水涨幅值salary_growth,并按照salary_growth逆序排列. 提示:在s ...

  7. SQL-15 查找employees表所有emp_no为奇数,且last_name不为Mary的员工信息,并按照hire_date逆序排列

    题目描述 查找employees表所有emp_no为奇数,且last_name不为Mary的员工信息,并按照hire_date逆序排列CREATE TABLE `employees` (`emp_no ...

  8. 51nod 1020 逆序排列 递推DP

    1020 逆序排列  基准时间限制:2 秒 空间限制:131072 KB 分值: 80 难度:5级算法题  收藏  关注 在一个排列中,如果一对数的前后位置与大小顺序相反,即前面的数大于后面的数,那么 ...

  9. 51nod 1020 逆序排列——dp

    在一个排列中,如果一对数的前后位置与大小顺序相反,即前面的数大于后面的数,那么它们就称为一个逆序.一个排列中逆序的总数就称为这个排列的逆序数. 如2 4 3 1中,2 1,4 3,4 1,3 1是逆序 ...

  10. 1020 逆序排列(DP)

    1020 逆序排列 基准时间限制:2 秒 空间限制:131072 KB 分值: 80 难度:5级算法题 在一个排列中,如果一对数的前后位置与大小顺序相反,即前面的数大于后面的数,那么它们就称为一个逆序 ...

随机推荐

  1. Django ImageField 内置属性height,width和size

    ImageField实例使用height,width和size属性后,若后继操作需重新打开实例,其他模块方法才能调用实例,使用open()方法:>>> from PIL import ...

  2. MySQL学习日志(建设中)

    1.前期准备 1.1软件需求 mysql8.0 Connector/J 8.0.31 workbench(懒得放链接自行百度吧) 一定不要下5.5或更低版本的,我折磨了宝贵的一上午,低版本bug很多, ...

  3. csr_matrix与ndarray类型互转

    ndarry 转 csr_matrix>>> import numpy as np>>> import scipy.sparse >>> my_m ...

  4. UltiSnips安装及设置

    2022-10-05 10:56:50 星期三 安装了UltiSnips插件,然后开始学习 第一个命令 UltiSnipsEdit 不好使,创建了~/.vim/UltiSnips 还是 can not ...

  5. 瑞士军刀 sox 系列 :给.raw文件添加header变身.wav文件

    1.先去安装 sox https://sourceforge.net/projects/sox/files/sox/ 2.将sox的安装目录加到系统path变量里. 3.开始执行命令 sox -t r ...

  6. nginx: the "ssl" parameter requires ngx_http_ssl_module in /usr/local/nginx/conf/nginx.conf

    Nginx如果未开启SSL模块,配置Https时将提示如题错误 原因:nginx缺少http_ssl_module模块,编译安装的时候带上--with-http_ssl_module配置就行了,但是现 ...

  7. Grafana + Prometheus 监控 Zookeeper

    废话不多说,前几篇已经相应的介绍Grafana 跟 Prometheus,如有不清楚,请参考: https://www.cnblogs.com/zgz21/p/12054518.html https: ...

  8. 简述47种Shader Map的渲染原理与制作方法

    https://mp.weixin.qq.com/s/6EVpmgC53HqklIVkIpEssg

  9. 用深度学习模型Word2Vec探索《红楼梦》人物关系

    先来看一看结果,发现: 1.贾宝玉和袭人的关系最近. 2.薛宝钗和自己的妈妈关系最近. 3.贾宝玉和林黛玉逼格比较统一,薛宝钗属于独树一帜的逼格调性. 4.大观园中可以看到邢岫烟经常出没... 还有更 ...

  10. 正在运行转换: System.Runtime.Remoting.RemotingException: 无法加载类型“EnvDTE._DTE

    在编写T4,引用envdte时,遇到如下错误,解决方案:右击引用中的envdte,属性中将"嵌入互操作类型"为false,重新编译库即可. 错误信息如下: 严重性    代码   ...