花了半天把二分查找的几种都写了一遍。验证了一下。二分查找的正确编写的关键就是,确保循环的初始、循环不变式能够保证一致。

可以先从循环里面确定循环不变式,然后再推导初始条件,最后根据循环不变式的内容推导出结果。

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的更多相关文章

  1. [Algorithms] Binary Search Algorithm using TypeScript

    (binary search trees) which form the basis of modern databases and immutable data structures. Binary ...

  2. 【437】Binary search algorithm,二分搜索算法

    Complexity: O(log(n)) Ref: Binary search algorithm or 二分搜索算法 Ref: C 版本 while 循环 C Language scripts b ...

  3. js binary search algorithm

    js binary search algorithm js 二分查找算法 二分查找, 前置条件 存储在数组中 有序排列 理想条件: 数组是递增排列,数组中的元素互不相同; 重排 & 去重 顺序 ...

  4. 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 ...

  5. 2 - Binary Search & LogN Algorithm

    254. Drop Eggs https://www.lintcode.com/problem/drop-eggs/description?_from=ladder&&fromId=1 ...

  6. [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 ...

  7. [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 ...

  8. [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 ...

  9. 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 ...

随机推荐

  1. 使用Solr索引MySQL数据

    环境搭建 1.到apache下载solr,地址:http://mirrors.hust.edu.cn/apache/lucene/solr/ 2.解压到某个目录 3.cd into D:\Solr\s ...

  2. java Clone 的心得记录

    我看有些类并没有实现Cloneable接口,这种情况下调用clone()方法也不try catch也不throws: 但是如果我自己这样搞,也不实现Cloneable,接口,直接调用clone()方法 ...

  3. Swift 获取屏幕宽高

    let screenh = UIScreen.mainScreen().applicationFrame.size.heightlet screenw = UIScreen.mainScreen(). ...

  4. jQuery简单入门

    jQuery是什么 John Resig在2006年1月发布的一款跨主流浏览器的JavaScript库,简化JavaScript对HTML操作为什么要使用jQuery (1)write less do ...

  5. linux shell basic command

    Learning basic Linux commands Command Description $ ls This command is used to check the contents of ...

  6. 给notepad++添加右键菜单

    Windows Registry Editor Version 5.00 [HKEY_CLASSES_ROOT\*\Shell\NotePad++] [HKEY_CLASSES_ROOT\*\Shel ...

  7. POJ 1160 题解

    Post Office Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 18835   Accepted: 10158 Des ...

  8. penpyxl basic function demo code

    Openpyxl basic function demo code demo code: #!/usr/bin/env python # -*- coding: utf-8 -*- "&qu ...

  9. HashMap实现缓存

    package com.cache; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.a ...

  10. hadoop---前期准备---屌丝

    hadoop要求有多台机子进行后续的数据处理,作为屌丝一枚,怎么才能搭建一个合适的环境学习hadoop?这就是本篇将要介绍的----前期准备. 搭建环境没啥好说的,说一下搭建环境多需要的吧 硬件:电脑 ...