经典查找算法之二分查找
来源:互联网 发布:大数据产品总监 编辑:程序博客网 时间:2024/05/17 03:14
二分查找
作为查找算法中最基础的查找算法,时间复杂度为O(logn)。前提是序列有序,每次取序列中位数跟关键字比较,相等则返回中位数所在位置索引;小于关键字,则在中位数位置之后的子序列中继续取子序列中位数同关键字比较;大于关键字,则在中位数位置之前的子序列中继续取该子序列的中位数同关键字比较。
二分查找C++实现代码如下:
// 二分查找#include <iostream>using namespace std;int BinarySearch(int *input, int goal, int len){if (input == nullptr || len <= 0) return -1;int low = 0;int high = len - 1;while (low <= high){int middle = (high - low) / 2 + low;if (input[middle] == goal){return middle;}else if (input[middle] > goal){high = middle - 1;}else{low = middle + 1;}}return -1;}int main(int argc, char *argv[]){int input[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };int goal = 6;if (BinarySearch(input,goal,9) != -1){cout << goal << "在数组中位置是:" << BinarySearch(input, goal, 9) << endl;}else{cout << goal + "不在数组中" << endl;}system("pause");return 0;}
1 0
- 经典查找算法之二分查找
- 【经典算法】二分查找
- 【经典算法】:二分查找
- 经典算法之二分查找法
- 查找算法之二分查找
- 查找算法之二分查找
- 查找算法之二分查找
- 查找算法之二分查找
- 查找算法之二分查找
- 查找算法之二分查找
- 查找算法之二分查找
- 查找算法之二分查找
- 查找算法之二分查找
- 算法之二分查找
- 算法之二分查找
- 算法之二分查找
- 经典算法之查找
- lintcode之经典二分查找
- 机器学习基础
- android:descendantFocusability
- 齐次坐标的理解
- 为什么export-->runnable jar file的launch configuration下拉没有东西 以及 清除Launch configuration的历史记录
- 【LeetCode】54. Spiral Matrix 解题报告
- 经典查找算法之二分查找
- servlet代码分析-整个执行流程
- MySql之空值与非空与自动编号以及约束
- gedit 备份功能
- Program3_S
- C++实现委托机制(二)
- 初始 java 反射机制 (一)
- 如何写软件设计文档
- android开发笔记之多媒体—SurfaceView