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. idea的小tip

    1. 校验正则表达式 String类型的matches方法中键入option+return选择 check regexp可以测试正则的正确性

  2. 浅谈Redis与分布式锁

    为什么需要分布式锁 Redis如何实现分布式锁 如何避免死锁? 锁被别人释放怎么办? 锁过期时间不好评估怎么办? Redlock 真的安全吗 为什么要在多个实例上加锁? 为什么大多数实例加锁成功,才算 ...

  3. 监听 view 初始化时

    new ViewTreeObserverRegister().observe(getContentView(), new ViewTreeObserver.OnGlobalLayoutListener ...

  4. 正则表达式re.compile()的使用

    re 模块提供了不少有用的函数,用以匹配字符串,比如: compile 函数match 函数search 函数findall 函数finditer 函数split 函数sub 函数subn 函数re ...

  5. php严格模式的使用

    <?php declare (strict_types = 1); namespace app\controller; use app\BaseController; use think\fac ...

  6. c#获取当前进程使用内存

    public static string GetMemory()        {            Process proc = Process.GetCurrentProcess();     ...

  7. pandas常用方法之read_excel详解

    前期准备 准备测试数据如下: fl_path = r"C:\Users\Desktop\test.xlsx" dic = { 'num': ['001', '002', '003' ...

  8. ue项目--浏览器出现卡顿及崩溃的原因查找与解决方案

    一些内存泄露的情况进行了排查 全局变量 定时器 使用未销毁的全局事件和第三方库 v-if和v-show不合理使用,v-if和v-for不合理使用 使用watch

  9. Little Tiger vs. Deep Monkey(hdu4815)01背包

    题:http://acm.hdu.edu.cn/showproblem.php?pid=4815 题意:已知n个题以及每个题答对的得分,给出p概率 小老虎vs小猴子答题:已知小猴子随机答题,请问老虎至 ...

  10. 5. Python 函数

    函数:(方法.功能) 作用:1.提高代码的复用性,2.让代码更简洁 函数命名方法   函数不调用是不会被执行的     def calc(a,b): #形参 #位置参数,必填,否则报错 res = a ...