Binary Search 的递归与迭代实现及STL中的搜索相关内容
与排序算法不同,搜索算法是比较统一的,常用的搜索除hash外仅有两种,包括不需要排序的线性搜索和需要排序的binary search。
首先介绍一下binary search,其原理很直接,不断地选取有序数组的组中值,比较组中值与目标的大小,继续搜索目标所在的一半,直到找到目标,递归算法可以很直观的表现这个描述:
int binarySearchRecursive(int A[], int low, int high, int key)
{
if (low > high) return -;
int mid = (low + high) >> ;
if (key < A[mid]) return binarySearchRecursive(A, low, mid - , key);
else if (key > A[mid]) return binarySearchRecursive(A, mid + , high, key);
else return mid;
}
但实际上,递归方法的时间效率和空间效率都不如迭代方法,迭代方法才是常用的binary search,代码如下:
int binarySearch(int A[], int low, int high, int key)
{
int mid;
while (low <= high)
{
mid = (low + high) >> ;
if (key < A[mid]) high = mid - ;
else if (key > A[mid]) low = mid + ;
else return mid;
}
return -;
}
简单计算一下Binary Search的效率:
算法流程:
1.检查上下边界--2.获取中值--3.比较--左半边进入子问题/右半边进入自问题/获得结果
1,2所需时间为常数时间,设为C。3阶段以一半的数据量重新运行函数,所以:
T(n)=T(n/2)+C
设n=2^k,则有T(2^k)=T(2^(k-1))+C=(T(2^(k-2))+C)+C=T(1)+k*C
即T(n)=log(n)*C+T(1),所以binary search是一个O(log(n))的算法。
测试函数:
void searchTest()
{
int a[] = { ,,,,,,,,,,, };
cout << binarySearch(a, , , ) << endl;
cout << binarySearch(a, , , ) << endl;
cout << binarySearch(a, , , ) << endl;
cout << endl;
cout << binarySearchRecursive(a, , , ) << endl;
cout << binarySearchRecursive(a, , , ) << endl;
cout << binarySearchRecursive(a, , , ) << endl;
}
测试结果如下:
11
-1
-1
11
-1
-1
请按任意键继续. . .
传统C函数中有bsearch这一函数,因为在现代C++中使用C库运行效率很低,加上接口并不好用,不再提及。而STL中,有以下几个关于搜索的函数。他们均作用于各个STL容器。
int count(起始迭代器,终止迭代器,key value)
return key value的数量
iterator find(起始迭代器,终止迭代器,key value)
成功:return 找到的第一个key value的迭代器
失败:return 终止迭代器
bool binary_search(起始迭代器,终止迭代器,key value)
return 是否找到
iterator lower_bound(起始迭代器,终止迭代器,key value)
return 大于或等于key value的第一个迭代器,若所有值都小于key value,返回终止迭代器
iterator upper_bound(起始迭代器,终止迭代器,key value)
return 大于key value的第一个迭代器,若所有值都小于key value,返回终止迭代器
这些函数中,count和find是作用于任意排序对象的,其效率为O(n),而binary_search, lower_bound, upper_bound是作用于有序对象的,其效率是O(logN)。
下面代码给出这些STL函数的测试:
void searchTest()
{
vector<int> b{ ,,,,,,,,,,, };
cout << "vector<int> b{ 1,2,3,4,4,7,9,11,17,20,23,39 };" << endl;
cout << "count(b.begin(), b.end(), 4):"
<< count(b.begin(), b.end(), ) << endl;
cout << endl;
cout << "find(b.begin(), b.end(), 39) - b.begin():"
<< find(b.begin(), b.end(), ) - b.begin() << endl;
cout << "find(b.begin(), b.end(), 4) - b.begin():"
<< find(b.begin(), b.end(), ) - b.begin() << endl;
cout << "find(b.begin(), b.end(), 37) - b.begin():"
<< find(b.begin(), b.end(), ) - b.begin() << endl;
cout << "find(b.begin() + 5, b.begin() + 10, 39) - b.begin():"
<< find(b.begin() + , b.begin() + , ) - b.begin() << endl;
cout << endl;
cout << "binary_search(b.begin(), b.end(), 39):"
<< binary_search(b.begin(), b.end(), ) << endl;
cout << "binary_search(b.begin(), b.end(), 37):"
<< binary_search(b.begin(), b.end(), ) << endl;
cout << endl;
cout << "lower_bound(b.begin(), b.end(), 39) - b.begin():"
<< lower_bound(b.begin(), b.end(), ) - b.begin() << endl;
cout << "lower_bound(b.begin(), b.end(), 4) - b.begin():"
<< lower_bound(b.begin(), b.end(), ) - b.begin() << endl;
cout << "lower_bound(b.begin(), b.end(), 37) - b.begin():"
<< lower_bound(b.begin(), b.end(), ) - b.begin() << endl;
cout << "lower_bound(b.begin() + 5, b.begin() + 10, 39) - b.begin():"
<< lower_bound(b.begin() + , b.begin() + , ) - b.begin() << endl;
cout << endl;
cout << "upper_bound(b.begin(), b.end(), 39) - b.begin():"
<< upper_bound(b.begin(), b.end(), ) - b.begin() << endl;
cout << "upper_bound(b.begin(), b.end(), 4) - b.begin():"
<< upper_bound(b.begin(), b.end(), ) - b.begin() << endl;
cout << "upper_bound(b.begin(), b.end(), 37) - b.begin():"
<< upper_bound(b.begin(), b.end(), ) - b.begin() << endl;
cout << "upper_bound(b.begin() + 5, b.begin() + 10, 39) - b.begin():"
<< upper_bound(b.begin() + , b.begin() + , ) - b.begin() << endl;
}
测试结果:
vector<int> b{ 1,2,3,4,4,7,9,11,17,20,23,39 };
count(b.begin(), b.end(), 4):2
find(b.begin(), b.end(), 39) - b.begin():11
find(b.begin(), b.end(), 4) - b.begin():3
find(b.begin(), b.end(), 37) - b.begin():12
find(b.begin() + 5, b.begin() + 10, 39) - b.begin():10
binary_search(b.begin(), b.end(), 39):1
binary_search(b.begin(), b.end(), 37):0
lower_bound(b.begin(), b.end(), 39) - b.begin():11
lower_bound(b.begin(), b.end(), 4) - b.begin():3
lower_bound(b.begin(), b.end(), 37) - b.begin():11
lower_bound(b.begin() + 5, b.begin() + 10, 39) - b.begin():10
upper_bound(b.begin(), b.end(), 39) - b.begin():12
upper_bound(b.begin(), b.end(), 4) - b.begin():5
upper_bound(b.begin(), b.end(), 37) - b.begin():11
upper_bound(b.begin() + 5, b.begin() + 10, 39) - b.begin():10
请按任意键继续. . .
Binary Search 的递归与迭代实现及STL中的搜索相关内容的更多相关文章
- Binary Search(Java)(递归)
public static int rank(int[] array, int k, int front, int rear) { if(front > rear) return -1; int ...
- 【Leetcode】【Medium】Validate Binary Search Tree
Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as ...
- Trie(前缀树)和ternary trie和binary search tree
1 什么是trie trie是一棵多叉树,假如存放的是由26个字母(不区分大小写)构成的字符串的话,那么就是一棵26叉树. trie树是一棵前缀树,因为每个结点只保存字符串中的一个字符,整个字符串保存 ...
- BINARY SEARCH 的一点说明
在sap 之abap语言中,有BINARY SEARCH这个查找条件.使用read table 来读取内表时,使用BINARY SEARCH可以大大的提高查找的效率,为什么呢?学过数据库的人会知道 ...
- (BST 递归) leetcode98. Validate Binary Search Tree
Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as ...
- 二叉树前序、中序、后序非递归遍历 144. Binary Tree Preorder Traversal 、 94. Binary Tree Inorder Traversal 、145. Binary Tree Postorder Traversal 、173. Binary Search Tree Iterator
144. Binary Tree Preorder Traversal 前序的非递归遍历:用堆来实现 如果把这个代码改成先向堆存储左节点再存储右节点,就变成了每一行从右向左打印 如果用队列替代堆,并且 ...
- 二分查找(Binary Search)的递归和非递归
Binary Search 有时候我们也把它叫做二进制查找 是一种较为高效的再数组中查找目标元素的方法 我们可以通过递归和非递归两种方式来实现它 //非递归 public static int bin ...
- Lowest Common Ancestor of a Binary Search Tree(Java 递归与非递归)
题目描述: Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in ...
- [LeetCode] Closest Binary Search Tree Value 最近的二分搜索树的值
Given a non-empty binary search tree and a target value, find the value in the BST that is closest t ...
随机推荐
- ZooKeeper实现分布式锁
使用场景 一般的锁是指单进程多线程的锁,在多线程并发编程中,用于线程之间的数据同步,保证共享资源的访问.而分布式锁,指的是在分布式环境下,保证跨进程.跨主机.跨网络的共享资源,实现互 ...
- Rust语言之HelloWorld Web版
Rust语言之HelloWorld Web版 下面这篇文章值得仔细研读: http://arthurtw.github.io/2014/12/21/rust-anti-sloppy-programmi ...
- my project 中git使用过程(基本操作流程)
1.g it clone git@name:server/BM/APPS.git 则BM_APPS.git项目被下载到当前目录下了,这时git@name:server/BM/APPS.git就是自己 ...
- Cocos2D绘制纹理的一般方法
如果你想在通常情况下绘制纹理,最简单的方法是在CCSprite的子类中实现.否则你将不得不自己创建一个CCRenderState对象传递给blend模式,着色器以及(可选的)纹理给CCRenderer ...
- LeetCode之“链表”:Intersection of Two Linked Lists
此题扩展:链表有环,如何判断相交? 参考资料: 编程判断两个链表是否相交 面试精选:链表问题集锦 题目链接 题目要求: Write a program to find the node at whic ...
- 打造你的开发神器——介绍Android Studio上的几个插件
这个月因为各种事情在忙,包括赶项目,回老家,还有准备旅游的事,所以应该写不了四篇博客了.今天介绍一下关于Android Studio 的几个好用的插件,都是我在用的,它们或能帮你节省时间,或者让你心情 ...
- zookeeper+kafka集群安装之二
zookeeper+kafka集群安装之二 此为上一篇文章的续篇, kafka安装需要依赖zookeeper, 本文与上一篇文章都是真正分布式安装配置, 可以直接用于生产环境. zookeeper安装 ...
- myeclipse和输入法冲突的问题
问题:在myeclipse中编写注释的时候,偶尔出现繁体字的现象令人头疼. 原因:myeclipse中格式化快捷键为"ctrl+shift+f" 与搜狗输入法快捷键冲突.按下后输入 ...
- Sample Code for Qp_preq_pub.Price_request Api to Simulate an Ask for Promotion Modifier
DECLARE p_line_tbl QP_PREQ_GRP.LINE_TBL_TYPE; p_qual_tbl QP_PREQ_GRP.QUAL_TBL_TYPE; p_line_attr_tbl ...
- LeetCode之“数学”:Rectangle Area
题目链接 题目要求: Find the total area covered by two rectilinear rectangles in a 2D plane. Each rectangle i ...