二进制搜索算法_使用安全摄像机镜头解释二进制搜索算法
二进制搜索算法
by Julia Geist
Julia·盖斯特(Julia Geist)
使用安全摄像机镜头解释二进制搜索算法 (Binary Search Algorithms explained using security camera footage)
Binary search, also known as half-interval search or logarithmic search, is a search algorithm that finds the position of a target value within a sorted array.
二进制搜索(也称为半间隔搜索或对数搜索)是一种搜索算法,用于查找排序数组中目标值的位置。
语境 (Context)
I used to live in a building that had a communal kitchen for over 100 students. As you might imagine, there were almost always dishes that weren’t washed in the sink. A group at my school pitched the idea to put up a Nest Cam to catch culprits and call them out on it using the Nest Cam feed.
我曾经住在一栋有公用厨房的大楼里,可容纳100多名学生。 就像您想象的那样,几乎总是有没有在水槽中洗过的盘子。 我学校的一个小组提出了创建一个Nest Cam来捕捉罪犯的想法,并使用Nest Cam feed将其召唤出来。
To illustrate my point, let’s say you found dirty dishes at 12 pm, and you hadn’t been in the kitchen for a day.
为了说明我的观点,假设您在中午12点发现了脏盘子,而您一天都没有在厨房里。
Think about the way that you would search for the person who left the dishes. Would you watch all 24 hours of footage, from the beginning, until you found the culprit?
考虑一下您寻找离开盘子的人的方式。 从头开始,直到发现罪魁祸首,您是否会观看所有24小时的录像?
Probably not. Most likely you’d be hopping around the footage, checking to see if the dishes were in the sink, say, 12 hours ago — at 12 am. If they were, then you’d know that it happened before 12 am. You might flip back to 10 pm after that. If the dishes aren’t there, you’ve now narrowed down the time frame from 10 pm to 12 am — in other words, you’ve ruled out any time before 10 pm. You’d continue this process until you found the culprit.
可能不是。 例如,您很可能会在画面上跳来跳去,例如12个小时前的凌晨12点,检查盘子是否在水池中。 如果是这样,那么您会知道它发生在上午12点之前。 之后,您可能会回到晚上10点。 如果菜都没有 ,你现在已经缩小的时限从10点至12点-换句话说,你已经晚上10点之前排除了任何时候。 您将继续此过程,直到找到罪魁祸首。
What would have taken you up to 24 hours, if you had watched the footage in its entirety, now only takes a few seconds.
如果您完整地观看了整个视频,那么最多需要24小时才能完成,现在只需几秒钟。
Whether you knew it or not, the specific process we just went through is a binary search! A binary search is a very specific way of hopping back and forth in the footage.
无论您是否知道,我们刚刚经历的特定过程都是二进制搜索! 二进制搜索是在素材中来回跳动的非常特定的方式。
Namely, the footage is split at its midpoint to check for the dishes each time. Notice how the distance to the midpoint gets exponentially smaller with each click.
即,镜头在其中点被分割以每次检查菜肴。 请注意,每次点击到中点的距离如何呈指数减小。
Binary searches are used to find elements quickly and efficiently. The catch, though, is that binary searches only work when the structure you’re looking through is sorted.
二进制搜索用于快速有效地查找元素。 不过,要注意的是, 二进制搜索仅在您浏览的结构被排序时才起作用 。
In the Nest Cam example, what is the footage sorted by? What are we looking for within that sorted arrangement?
在Nest Cam示例中,素材按什么排序? 我们在这种排序安排中寻找什么?
In this case, the data we are searching is sorted by time. Time allows for a linear measurement. Therefore, it allows us to perform a binary search to find someone who doesn’t wash their dishes within a matter of seconds.
在这种情况下,我们正在搜索的数据将按时间排序。 时间允许进行线性测量。 因此,它使我们可以执行二进制搜索来查找在几秒钟内不洗碗的人。
We also need something that we’re looking for. In this case, it’s the presence of unwashed dishes in the communal sink.
我们还需要寻找的东西。 在这种情况下,公共水槽中存在未洗碗。
二进制搜索算法 (Binary Search Algorithm)
While programming, a binary search can be used in a multitude of contexts. It’s an extremely quick way to find elements within a sorted structure.
在编程时,可以在多种环境中使用二进制搜索。 这是在排序的结构中查找元素的非常快速的方法。
Binary searches can be implemented in an iterative or recursive fashion. An iterative implementation uses a while
loop. Meanwhile, a recursive implementation will call itself from within its own body.
二进制搜索可以迭代或递归的方式实现。 迭代实现使用while
循环。 同时,递归实现将在其自身内部进行调用。
In code, I’ll be performing a binary search on a relatively simple, sorted set of data to highlight the core implementation of a binary search.
在代码中,我将对相对简单的排序数据集执行二进制搜索,以突出显示二进制搜索的核心实现。
Given an array of sorted numbers, return True
if 53 is an element.
给定一个有序数字数组,如果53是一个元素,则返回True
。
[0, 3, 4, 5, 6, 15, 18, 22, 25, 27, 31, 33, 34, 35, 37, 42, 53, 60]
迭代式 (Iterative)
In the iterative approach, a while loop runs until the range of possibilities is zero. This is done by changing the upper and lower bounds of where we are looking and calculating the middle index of that range.
在迭代方法中,运行while循环直到可能性范围为零。 这是通过更改我们所查看位置的上限和下限并计算该范围的中间索引来完成的。
The range exists between the lower and upper bounds, inclusive of the bounds themselves.
范围存在于上下限之间,包括上限本身。
Before the while
loop begins, the lower bound is zero and the upper bound is the length of the array. The upper bound changes if the number we’re looking for is in the first half of the range. The lower bound changes if the number we’re looking for is in the second half of the range.
在while
循环开始之前,下限为零,上限为数组的长度。 如果我们要查找的数字在范围的前半部分,则上限会更改。 如果我们要查找的数字在范围的下半部,则下界会改变。
If the while
loop finishes, meaning there is a range of length zero, return False
.
如果while
循环结束,这意味着长度范围为零,则返回False
。
def binarySearch(array, number): lowerBound = 0 upperBound = len(array)
while lowerBound < upperBound: middleIndex = int(math.floor(lowerBound + (upperBound — lowerBound) / 2)) if array[middleIndex] == number: return True elif array[middleIndex] < number: lowerBound += 1 elif array[middleIndex] > number: upperBound = middleIndex return False
I’d like to elaborate on this equation:
我想详细说明这个等式:
int(math.floor(lowerBound + (upperBound — lowerBound) / 2))
int(math.floor(lowerBound + (upperBound — lowerBound) / 2))
The length of the range is calculated by subtracting the lower bound from the upper bound. However, knowing how long the range is isn’t enough.
的长度 范围是通过从上限减去下限来计算的。 但是,仅知道范围多远是不够的。
At this point, we don’t know which indexes to check in the array. So we are shifting up the array by the lower bound.
在这一点上,我们不知道要检查数组中的索引。 因此,我们将数组上移下限。
We then divide that by two, and round down, to get the middle index of the range. math.floor
returns a float
, so we also have to cast the result to an int
.
然后,我们将其除以2,然后向下舍入以获得该范围的中间索引。 math.floor
返回一个float
,因此我们还必须将结果转换为int
。
递归的 (Recursive)
In the recursive approach, the function will call itself from within its body.
在递归方法中,该函数将在其体内调用自身。
The upper bound in this function is the length of the array passed in. Again, the upper bound changes if the number we’re looking for is in the first half of the array. The lower bound changes if the number we’re looking for is in the second half of the array.
此函数的上限是传入的数组的长度。同样,如果我们要查找的数字在数组的前半部分,则上限也会改变。 如果我们要查找的数字在数组的后半部分,则下界会改变。
def binarySearch(array, number): middleIndexOfArray = int(math.floor(len(array) / 2)) if middleIndexOfArray == 0: return False
if array[middleIndexOfArray] == number: return True elif array[middleIndexOfArray] > number: return binarySearch(array[:middleIndexOfArray], number) elif array[middleIndexOfArray] < number: return binarySearch(array[middleIndexOfArray:], number)
The function then calls itself, passing in an argument of an array half the length of the array that was its argument.
然后,该函数调用自身,传入一个数组实参,该数组实参的长度是该数组实参的一半。
If there are zero elements in the array, return False
.
如果数组中的元素为零,则返回False
。
The code is available on my Algorithms and Data Structures repo — star it to stay updated!
该代码在我的算法和数据结构存储库中可用-对其加注星标以保持更新!
下一步 (Next Steps)
I wrote my first binary search to implement a stochastic sampling algorithm. It generates a sentence based on the frequency of words in a corpus of text.
我编写了第一个二进制搜索以实现随机采样算法。 它根据文本语料库中单词的出现频率生成一个句子。
Feel free to try and build a similar project, which has quite a bit of prep before you can implement the binary search. Or think of your own projects and share them in the comments!
随意尝试构建一个类似的项目,该项目在实现二进制搜索之前已经做了很多准备。 或考虑自己的项目并在评论中分享!
This is the second post of my algorithm and data structures series. In each post, I’ll present a problem that can be better solved with an algorithm or data structure to illustrate the algorithm/data structure itself.
这是我的算法和数据结构系列的第二篇文章。 在每篇文章中,我将介绍一个可以通过算法或数据结构更好地解决的问题,以说明算法/数据结构本身。
Star my algorithms repo on Github and follow me on Twitter if you’d like to follow along!
在Github上为我的算法存储库加注星标,如果您想跟随我,在Twitter上关注我!
翻译自: https://www.freecodecamp.org/news/binary-search-algorithm-7170ae244438/
二进制搜索算法
相关文章:

Codeforces 460E Roland and Rose(暴力)
题目链接:Codeforces 460E Roland and Rose 题目大意:在以原点为圆心,半径为R的局域内选择N个整数点,使得N个点中两两距离的平方和最大。 解题思路:R最大为30。那么事实上距离圆心距离最大的整数点只是12个最多&#x…

HTML POST提交参数给PHP并返回json,上传execl文件
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文: 需求:AJAX post带参数请求接口,PHP接收后存入数据库;然后返回json数据循环渲染到HTML <!DOCTYPE html> <html lang"zh">&l…

在Ubuntu 12.04 桌面上设置启动器(快捷方式)
在Ubuntu 12.04 桌面上设置启动器(快捷方式)过程讲解: 如下图所示,Eclipse 和 SQLDeveloper 都可以直接双击打开,这些应用程序的启动器都在 /usr/share/applications文件夹下面,进入后将其复制到桌面即可。…

rxswift中hud_如何在RxSwift中运行测试
rxswift中hudby Navdeep Singh通过Navdeep Singh 如何在RxSwift中运行测试 (How to run tests in RxSwift) RxTest and RxBlocking are part of the RxSwift repository. They are made available via separate pods, however, and so require separate imports.RxTest和RxBlo…

安装完DevExpress14.2.5,如何破解它呢?
DevExpress是一个界面控件套件,提供了一系列的界面控件套件的DotNet界面控件。DevExpress开发的控件有很强的实力,不仅功能丰富,应用简单,而且界面华丽,更可方便订制,方便开发人员开发。 下面介绍DevExpres…

Extjs Ext.TreePanel
TreePanel 简单实例。 <link rel"stylesheet" href"Js/ext-4.2/resources/css/ext-all-neptune.css"/><script src"Js/jQuery/jquery-1.8.2.min.js" type"text/javascript"></script><script src"Js/ext-…

php模糊搜索功能
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文: 前端 前端post请求并发送str参数>搜索的内容; PHP <?phpheader("Content-Type:text/html;charsetutf8"); header("Access-Control-Allow-Origin…

react 快速上手开发_React中测试驱动开发的快速指南
react 快速上手开发by Michał Baranowski通过MichałBaranowski React中测试驱动开发的快速指南 (A quick guide to test-driven development in React) Following the principles of Test-Driven Development (TDD) when writing a front-end React app might seem more dif…

iOS 相册和网络图片的存取
iOS 相册和网络图片的存取 保存 UIImage 到相册 UIKit UIKit 中一个古老的方法,Objective-C 的形式 void UIImageWriteToSavedPhotosAlbum(UIImage *image, id completionTarget, SEL completionSelector, void *contextInfo); 保存完成后,会调用 comple…

微信小程序实时聊天之WebSocket
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文: 1.所有监听事件先在onload监听。 // pages/index/to_news/to_news.js var app getApp(); var socketOpen false; var SocketTask false; var url ws://192.168.0.120:7011; Page…

webform repeater
repeater:由模板构成,解析后模板就不存在了 需要指定数据源进行数据绑定 List<Fruit> list new FruitDA().Select(); // 数据查询 (随便查寻的) Repeater1.DataSource list; // 赋值 Repeater1…

远程协助软件开发_这是我从事远程软件开发人员工作的主要技巧
远程协助软件开发by Colin Morgan通过科林摩根(Colin Morgan) 这是我从事远程软件开发人员工作的主要技巧 (Here are the top tips I’ve used to land a remote software developer job) Applying for a remote software developer job means you are voluntarily choosing t…

简谈-Python一些常用的爬虫技巧
第一种:基本的网页抓取 get方法 import urllib2url "链接response urllib2.urlopen(url)print response.read() post方法 import urllibimport urllib2url "链接form {name:abc,password:1234}form_data urllib.urlencode(form)request urllib2.Req…

微信小程序画布圆形进度条demo
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文: wxml <!--pages/test/test.wxml--> <canvas style"width: 300px; height: 200px;" canvas-id"canvasid"></canvas>js // pages/test/test.js …

smarty 模板引擎
http://blog.csdn.net/zuiaituantuan/article/details/5951242 http://wenku.baidu.com/link?url-UHlSnTXOOAjFG1KjX6T9sEG6V4hNAMfRDpMuRRnc_FKbFAxiE5Ntk4lzxSm-7Z531uWdfvgYx81sdC61SgTZm7q8FdUt3gSs7ZlC0JR1SW转载于:https://www.cnblogs.com/hxjbc/p/4441879.html

flask url构建_如何为生产构建构建Flask-RESTPlus Web服务
flask url构建by Greg Obinna由格雷格奥比纳(Greg Obinna) 如何为生产构建构建Flask-RESTPlus Web服务 (How to structure a Flask-RESTPlus web service for production builds) In this guide I’ll show you a step by step approach for structuring a Flask RESTPlus web…

【2017-4-26】Winform 公共控件 菜单和工具栏
作废 等待重写 名称 功能取值赋值备注Button按钮多用来触发点击事件 CheckBox多选按钮 CheckedListBox多选按钮组 ComboBox下拉列表 DateTimePicker指定的格式选择时间日期 Lable说明性文字控件 LinkLable超链接类型文件控件 ListBox用户选择项 ListVie…

微信小程序限制当前位置和目的地的距离
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文: 1。获取当前位置经纬度 onLoad: function (options) {var that this;campaign_id campaign_idwx.getLocation({type: wgs84,success: function (res) {console.log(res)lat1 res.l…

命令行的全文搜索工具--ack
想必大家在命令行环境下工作时候,一定有想要查找当前目录下的源代码文件中的某些字符的需求,这时候如果使用传统方案,你可能需要输入一长串的命令,比如这样: 1. grep -R string dir/ 或者 grep -r -e string direct…

ecmascript_TC39及其对ECMAScript的贡献
ecmascriptby Parth Shandilya通过Parth Shandilya TC39及其对ECMAScript的贡献 (TC39 and its contributions to ECMAScript) Many people get confused about what is JavaScript and what is ECMAScript. Sometimes it’s hard to tell how they are connected with each o…

Winio驱动在64位windows下无法使用的解决方法
C#在使用WinIo的驱动开发类似按键精灵一类工具的时候,需要对相关的驱动进行注册才能正常启动,找了下资料,资料来自: http://jingyan.baidu.com/article/642c9d34e55bd9644b46f74e.html 我在这里进行转载: Winio驱动在6…

js获取前后几天或者前后几个月的日期
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 ; 正文: demo: 1.获取前后几天的日期 // pages/test/test.jsPage({onLoad: function (options) {var day -7;console.log(GetDay(day))}, }) function GetDay(day) {var tim…

nodejs安装、配置及开发工具
学了node一段时间,但是node的安装还是有一点迷糊。今天新换电脑,所以,需要从头开始,发现node的安装还是不顺畅,这篇随笔是之前学的时候写,但是今天再打开看的时候,发现其他好像没有什么内容&…

拨测工具_您可以拨多少钱? 快速简单地介绍有用的工具。
拨测工具by Miguel Bustamante通过Miguel Bustamante 您可以卷曲多少? 快速简单地介绍有用的工具。 (How much can you cURL? A quick and easy intro to a useful tool.) On a good day I can flex a 20 lb weight…twice. Probably. But that’s not the type o…

leetcode第一刷_Recover Binary Search Tree
这是一道好题,思路尽管有,可是提交之后总是有数据过不了,又依照数据改改改。最后代码都没法看了。收到的教训是假设必须为自己的代码加上非常多非常多特殊的限定。来过一些特殊的数据的话。说明代码本身有非常大的漏洞。 这道题,我…

Java中的文件路径
通常情况下,在Java项目中,我们使用的路径都是在拿到类加载路径后,根据相对位置,使用 FilePathTest.class.getResourceAsStream(relativePath);拿到文件。今天小生不使用classPath,而是直接去使用相对路径来…

js上传文件,上传表单demo 包含后端php
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文: <!DOCTYPE html> <html lang"zh"><head><meta charset"UTF-8"><title>Title</title><script src"https://ajax.as…

如何在Tensorflow.js中处理MNIST图像数据
by Kevin Scott凯文斯科特(Kevin Scott) 如何在Tensorflow.js中处理MNIST图像数据 (How to deal with MNIST image data in Tensorflow.js) There’s the joke that 80 percent of data science is cleaning the data and 20 percent is complaining about cleaning the data …

常用图像额文件格式及类型
1、显示一幅二值图像: >> bw zeros(90,90); >> bw(2:2:88,2:2:88) 1; >> imshow(bw); >> 2、利用image函数显示一幅索引图像: >> [X,MAP] imread(E:\STUDY_software\Matlab2016\images\11.jpg); >> image(X); &…

微信小程序实现滑动翻页效果源码附效果图
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文: 微信小程序实现滑动翻页效果 效果图: 源码: <view class"mainFrame"><swiper class"container" indicator-dots"{{indic…