Algorithm | Binary Search
花了半天把二分查找的几种都写了一遍。验证了一下。二分查找的正确编写的关键就是,确保循环的初始、循环不变式能够保证一致。
可以先从循环里面确定循环不变式,然后再推导初始条件,最后根据循环不变式的内容推导出结果。
1. 普通的二分查找
第一版本:
//first version
int find(int arr[], int n, int target) {
int l = , r = n - ;
while (l <= r) {
int m = l + (r - l) / ;
if (arr[m] == target) return m;
else if (arr[m] < target) {
l = m + ;
} else {
r = m - ;
}
}
return -;
}
循环内部有三次比较,一般来说,相等的操作只需要判断一次,所以最好是放在循环最外面判断。
注意这里因为提到外面判断相等的情况了,那么循环退出条件就可以改为l <r, 在循环中不需要判断l == r的情形。
//second version
int findLeft(int arr[], int n, int target) {
int l = , r = n - ; // [l, r]
while (l < r) {
int m = l + (r - l) / ; // l < r => m < r
if (arr[m] < target) {
l = m + ; // l <= m => l need to be added by one ensuring l is always increasing; and arr[l] <= target
} else {
r = m; // target <= arr[m], [l, r], m < r => if arr[m] == target, we still decrease r, so what we found is the lower_bound
}
} // [l, r] && r >= l => if (arr[l] == target) => return l;
if (l < n && arr[l] == target) return l;
else return -;
}
2. 查找最左边的值
同上面的version 2.
关键就是,处理相等的情况。由于是要求最左的位置,所以遇到相等时候,仍要把区间往左移。所以这里是用了r=m。(因为m恒小于r)。
3. 查找最右边的值
这里的关键同样是处理相等的情况。要求的是最右的位置,那么遇到相等的时候,还是要把区间右移,所以这里是l=m+1。之所以要加1,就是因为l<=m的,为了确保循环一定能够退出,要加1,才能确保每次循环,区间都在缩小。但是加了1之后,变成了target==arr[m]的时候,l=m+1, 也就是target > arr[l]。所以最终的结果就是l-1。从这里再去推导初始化的时候,l和r的取值。因为区间是[l-1,r),所以l=1,r=n。
int findRight(int arr[], int n, int target) {
int l = , r = n;
// [l - 1, r)
while (l < r) {
int m = l + (r - l) / ;
if (arr[m] > target) { // ensuring target < arr[r] && target > arr[l], [l - 1, r)
r = m; // l < r => m < r, [l - 1, r)
} else {
l = m + ; // l <= m, when target == arr[m], l is still increasing, [l - 1, r), target >= arr[l - 1] = arr[m]
}
}
// [l-1, r)
if (l - >= && arr[l - ] == target) return l - ;
else return -;
}
4. 查找倒数第一个比它小的数;
int findLastSmall(int arr[], int n, int target) {
int l = , r = n - ;
// [l, r]
while (l < r) {
int m = l + (r - l) / ;
if (arr[m] >= target) {
r = m; // target <= arr[r]
} else {
l = m + ; // target > arr[m] => target >= arr[m+1], [l, r]
}
}
// target is in [l, r], so the last smaller number is r
if (target > arr[l]) return l;
return l - ;
}
因为循环中确保了target >= arr[l] && target <= arr[r],那么我们要判断target[l]是否等于target,如果等于,返回的是l-1。否则返回的就是l。
5. 查找第一个比它大的数;
int findFirstLarge(int arr[], int n, int target) {
int l = , r = n;
// [l - 1, r)
while (l < r) {
int m = l + (r - l) / ;
if (arr[m] <= target) { // target >= arr[l - 1]
l = m + ; // l is increasing, [l - 1, r)
} else { // target < arr[m]
r = m; // target < arr[r],[l - 1, r)
}
}
// target is in [l - 1, r), so the first larger number is r
return r;
}
这个比较简单,因为循环确定target>=arr[l]&&target < arr[r],那么第一个比target大的数肯定就是arr[r]。
Worst case performance: O(log n)
Best case performance: O(1)
Average case performance: O(log n)
Worst case space complexity: O(1)
今天算是把怎么验证程序的正确性研究了一天了。。。20140923
Algorithm | Binary Search的更多相关文章
- [Algorithms] Binary Search Algorithm using TypeScript
(binary search trees) which form the basis of modern databases and immutable data structures. Binary ...
- 【437】Binary search algorithm,二分搜索算法
Complexity: O(log(n)) Ref: Binary search algorithm or 二分搜索算法 Ref: C 版本 while 循环 C Language scripts b ...
- js binary search algorithm
js binary search algorithm js 二分查找算法 二分查找, 前置条件 存储在数组中 有序排列 理想条件: 数组是递增排列,数组中的元素互不相同; 重排 & 去重 顺序 ...
- 2 - Binary Search & LogN Algorithm - Apr 18
38. Search a 2D Matrix II https://www.lintcode.com/problem/search-a-2d-matrix-ii/description?_from=l ...
- 2 - Binary Search & LogN Algorithm
254. Drop Eggs https://www.lintcode.com/problem/drop-eggs/description?_from=ladder&&fromId=1 ...
- [Algorithm] Delete a node from Binary Search Tree
The solution for the problem can be divided into three cases: case 1: if the delete node is leaf nod ...
- [Algorithm] Check if a binary tree is binary search tree or not
What is Binary Search Tree (BST) A binary tree in which for each node, value of all the nodes in lef ...
- [Algorithm] Count occurrences of a number in a sorted array with duplicates using Binary Search
Let's say we are going to find out number of occurrences of a number in a sorted array using binary ...
- leetcode -- Convert Sorted List to Binary Search Tree
Given a singly linked list where elements are sorted in ascending order, convert it to a height bala ...
随机推荐
- 其原因可能是堆被损坏,这说明 100BloodCellSegTest.exe 中或它所加载的任何 DLL 中有 Bug。
这个问题可能是内存空间释放了两次,比如使用cvLoadImage函数时IplImage* img = cvLoadImage(buf.c_str(),1);,注意要释放内存,但不要释放了两次cvRel ...
- Jquery判断变量是否为空
var aaa=''; if(aaa) { //aaa不为空也不是不可识别对象时执行 } else { //aaa为空或不可识别时执行 } aaa必须是变量,对象的属性好像是不行,
- FFT与乒乓球
刚刚打乒乓球的时候,看到一个旋球.想起<傅里叶分析之掐死教程>: “正弦曲线波叠加出一个带90度角的矩形波来” 我们把多个旋叠加在一起,是不是就可以让这个球跳舞了呢?
- OS X 下不通过Homebrew安装ASP.NET 5开发环境
在 ASP.NET 的 Home repo 里,推荐使用 Homebrew 安装开发环境,不过我的电脑里已经有 ports 了,这应该是当年用 rvm 安装 Ruby 时悄悄地装上的吧.不管怎样,作为 ...
- UVALive 2453 Wall (凸包)
题意:给你一个多边形的城堡(多个点),使用最短周长的城墙将这个城堡围起来并保证城墙的每个点到城堡上的每个点的距离都不小于l 题解:因为两点间的直线一定比折线短,所以这样做 先使用所有点求得一个凸包,接 ...
- 在powerdesigner中创建物理数据模型
物理数据模型(PDM)是以常用的DBMS(数据库管理系统)理论为基础,将CDM/LDM中所建立的现实世界模型生成相应的DBMS的SQL语言脚本.PDM叙述数据库的物理实现,是对真实数据库的描述 PDM ...
- js/jQuery使用过程中常见问题
目录 一.jQuery选择器选择选中的或者disabled的选择框时attr函数无效 二.jQuery each函数的break/continue 三.jQuery 获取元素的left会值/left数 ...
- SparkLauncher 1.6 版本bug
背景 近期在研究使用java api的方式来调用Spark程序,通过句柄的方式来完成监控Job运行状态.及时杀死Job等功能.官方文档直接指出使用Java/Scala创建Job的方式——利用Spark ...
- 2016-1-28 图解HTTP(03)
6.2.5 非HTTP/1.1首部字段 不限于RFC2616中定义的47种首部字段,还有Cookie.Set-Cookie和Content-Disposition等在其他RFC中首部字段 ...
- C到C++的升级
const 在C中只是个“只读变量”,并不是真正意义上的常量,通过指针能改变它,如下 #include<stdio.h> int main() { ;//声明只读变量a为0 int* p= ...