整理及总结二分查找的判断和边界细节

修改版

package com.leej.binarysearch;

import java.util.Arrays;

/**
* @author jerry
* @create 17/10/7 12:21
*/
public class BinarySearch { public static int BinarySearch(int[] nums, int key) {
int start = 0, end = nums.length - 1;
int mid;
while(start <= end) {
mid = (start + end) >> 1;
if (nums[mid] == key) return mid;
else if (nums[mid] > key)
end = mid -1;
else
start = mid + 1;
}
return -(start + 1);
} public static int LowerBound(int[] nums, int key) {
int first = 0, last = nums.length;
int mid;
while(first < last) {
mid = (first + last) >> 1;
if (nums[mid] < key) {
first = mid + 1;
} else {
last = mid;
}
}
return first;
} public static int UpperBound(int[] nums, int key) {
int first = 0, last = nums.length;
int mid;
while(first < last) {
mid = (first + last) >> 1;
if (nums[mid] <= key) {
first = mid + 1;
} else {
last = mid;
}
}
return first;
} public static void showArrays(int[] nums) {
for(int num : nums) System.out.print(num + " ");
System.out.println(); }
public static void main(String[] args) {
int[] nums = {10,20,30,30,20,10,10,20, 10};
Arrays.sort(nums); //10 10 10 20 20 20 30 30
showArrays(nums);
//System.out.println( BinarySearch(nums, 11) );
System.out.println(LowerBound(nums, 21));
System.out.println(UpperBound(nums, 21));
}
}

实现

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Arrays;
import java.lang.String;
/**
* @author jerry
* @create
*/
public class test {
public static void showArray(int[] nums) {
if (nums == null || nums.length == 0) return; for (int nu : nums)
System.out.printf("%d ", nu);
System.out.println();
} /**
* 循环条件left<=right, 所以left != mid , right != mid;
* 双闭区间[left, right]
**/
public static int binarySearch(int[] nums, int target) {
int left = 0, right = nums.length - 1, mid; //search range [left, right],闭区间
while(left <= right) {
mid = (left + right) >> 1;
if (nums[mid] == target)
return mid;
else if (nums[mid] < target)
left = mid + 1;
else
right = mid - 1;
}
return -1;
} /**
**STL 版本lower_bound
* 找到第一个大于等于target的数, in range [first, last), 左开右闭区间
**/
public static int lower_bound(int[] nums, int target) {
int first = 0, last = nums.length;
int mid, len, step;
len = last - first;
while(len > 0) {
step = len >> 1;
mid = first + step;
if (nums[mid] < target) { //[mid + 1, last)
first = mid + 1;
len -= step + 1;
} else { //[first, mid)最后可取边界mid
len = step;
}
}
return first;
} //找到第一个大于等于target
public static int my_lower_bound(int[] nums, int target) {
int first = 0, last = nums.length, mid;
//in ranget [first, last)
while(first < last) {
mid = (first + last) >> 1;
if (nums[mid] < target) { //[mid+1, last)
first = mid + 1;
} else {
last = mid;
}
}
return first;
} //找到第一个大于target的数
public static int my_upper_bound(int[] nums, int target) {
int first = 0, last = nums.length, mid;
//in range [first, last)
while(first < last) {
mid = (first + last) >> 1;
if (nums[mid] <= target) {
first = mid + 1;
} else {
last = mid;
}
}
return first;
} public static void main( String args[] ){
int[] nums = {10,20,30,30,20,10,10,20, 10};
Arrays.sort(nums); //10 10 10 20 20 20 30 30
test.showArray(nums);
System.out.println( test.binarySearch(nums, 11) );
System.out.println( test.my_lower_bound(nums, 20) );
System.out.println( test.lower_bound(nums, 20) );
System.out.println( test.my_upper_bound(nums, 20) );
}
} //#output
// 10 10 10 10 20 20 20 30 30
// -1
// 4
// 4
// 7

References

  1. http://www.cplusplus.com/reference/algorithm/lower_bound/
  2. http://www.cplusplus.com/reference/algorithm/upper_bound/
  3. http://www.cplusplus.com/reference/algorithm/binary_search/

二分查找、upper_bound、lower_bound的更多相关文章

  1. C++二分查找:lower_bound( )和upper_bound( )

    #include<algorithm>//头文件 //标准形式 lower_bound(int* first,int* last,val); upper_bound(int* first, ...

  2. 二分查找(lower_bound和upper_bound)

    转载自:https://www.cnblogs.com/luoxn28/p/5767571.html 1 二分查找 二分查找是一个基础的算法,也是面试中常考的一个知识点.二分查找就是将查找的键和子数组 ...

  3. 二分查找确定lower_bound和upper_bound

    lower_bound当target存在时, 返回它出现的第一个位置,如果不存在,则返回这样一个下标i:在此处插入target后,序列仍然有序. 代码如下: int lower_bound(int* ...

  4. 关于二分查找 使用 lower_bound

    在寻找单调递增最长自序列 , 的时候能不能确认出来哪个是单调递增最长自序列  ?  我的想法是 if(location>=num) dp[location]=b; 这样的 , 基于http:// ...

  5. LeetCode:Search Insert Position,Search for a Range (二分查找,lower_bound,upper_bound)

    Search Insert Position Given a sorted array and a target value, return the index if the target is fo ...

  6. CodeForces - 600B Queries about less or equal elements (二分查找 利用stl)

    传送门: http://codeforces.com/problemset/problem/600/B Queries about less or equal elements time limit ...

  7. I Count Two Three(打表+排序+二分查找)

    I Count Two Three 二分查找用lower_bound 这道题用cin,cout会超时... AC代码: /* */ # include <iostream> # inclu ...

  8. STL 二分查找三兄弟(lower_bound(),upper_bound(),binary_search())

    一:起因 (1)STL中关于二分查找的函数有三个:lower_bound .upper_bound .binary_search  -- 这三个函数都运用于有序区间(当然这也是运用二分查找的前提),以 ...

  9. STL中的二分查找———lower_bound,upper_bound,binary_search

    关于STL中的排序和检索,排序一般用sort函数即可,今天来整理一下检索中常用的函数——lower_bound , upper_bound 和 binary_search . STL中关于二分查找的函 ...

  10. 二分查找法(binary_search,lower_bound,upper_bound,equal_range)

    binary_search(二分查找) //版本一:调用operator<进行比较 template <class ForwardIterator,class StrictWeaklyCo ...

随机推荐

  1. [软件工程基础]2017.11.05 第九次 Scrum 会议

    具体事项 项目交接燃尽图 每人工作内容 成员 已完成的工作 计划完成的工作 工作中遇到的困难 游心 #10 搭建可用的开发测试环境:#9 阅读分析 PhyLab 后端代码与文档:#8 掌握 Larav ...

  2. Sonya and Matrix Beauty Codeforces - 1080E

    https://codeforces.com/contest/1080/problem/E 比赛时候一个多小时码不出来... 来看遇到的困难: 1.没有能用的随机unsignedlonglong函数 ...

  3. python之字典的相关操作

    一.什么是字典 dict 用{}表示,用来存放键值对数据 {key:value} 键:具有唯一性,不能重复,不可变 必须是可哈希的(不可变的数据类型) 字典是无序的,没有索引 值: 没有任何限制 已知 ...

  4. eclipse plugin

    快速查看目录 org.sf.easyexplore_1.0.4.jar mongo DB net.jumperz.app.MMonjaDB_1.0.16.jar jasper report jaspe ...

  5. Netty(1-1)Discard

    一.DiscardServerHandler import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext ...

  6. C++析构函数造成Debug Assertion Failed的问题

    昨天写了两个程序,均出现了析构函数造成Debug Assertion Failed的问题,由于是初学c++怎么想也想不通问题出在哪里.今天早上经人指点终于明白问题所在了.下面贴出代码和问题解析:(以下 ...

  7. PHP针对二维数组无限遍历变形研究

    一.需要变形的二维数组 $arr = Array( Array ( 'material_id' => 1, 'material_name' => '铜板纸', 'parent_id' =& ...

  8. 关于dopost和doget中文乱码问题

    1.doPost方法请求方式为Post 请求内容中包含请求体,因此解决方法较简单,只要改变请求体的编码即可,具体方法setCharacterEncoding("utf-8"); 2 ...

  9. MySQL表的碎片整理和空间回收小结

    MySQL表碎片化(Table Fragmentation)的原因 关于MySQL中表碎片化(Table Fragmentation)产生的原因,简单总结一下,MySQL Engine不同,碎片化的原 ...

  10. python+selenium之数据库连接

    首先要安装Python和MySQL的连接工具 下载地址如下: https://pypi.python.org/pypi/PyMySQL https://github.com/PyMySQL/PyMyS ...