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

修改版

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. linux 初始配置(centos)-网络和可视化界面

    1. 执行命令查看ip:ip addr 2. 如果没有或取到,要查看网卡是否启动,及ip配置是否正确,请先将ONBOOT改成yes,表示开机即启动 [lobin@localhost ~]$ cat / ...

  2. shell编程 条件判断式----利用 if .... then ----多重

    条件判断式----利用 if .... then ----多重 在同一个数据的判断中,如果该数据需要进行多种不同的判断时,应该怎么作?举例来说,上面的 sh06.sh 脚本中,我们只要进行一次 $yn ...

  3. ubuntu 设置字符集 locale(解决乱码问题)

    1.locale 查看现在的locale配置环境 2.localepurge 配置需要的locale(如果没有这个命令,用apt-get install localepurge安装) 3.locale ...

  4. Floyd判圈法

    ---恢复内容开始--- http://blog.csdn.net/ruoruo_cheng/article/details/53100656 ---恢复内容结束---

  5. windows环境下memcache配置方法 详细篇

    将memcache服务器安装包解压到C:\memcached文件夹后,使用cmd命令窗口安装. 1>开始>运行:CMD(确定) 2>cd C:\memcached(回车) 3> ...

  6. sqlsever 判断某个字段出现重复的字母或字符

    -------下面使用标量值函数判断  出现重复的个数 create function fn_str_times(@str varchar(1000),--原子符串@indexstr varchar( ...

  7. Linux mount实际使用

    查看所有文件系统(设备):fdisk -l 1.当要重新挂载一个文件系统时(设备):可以直接 #mount -o remount,rw /dev/sdb9/(文件系统) /mnt/sdb9/(目录) ...

  8. 使用 h5 新特性,轻松监听任何 App 自带返回键

    var hiddenProperty = 'hidden' in document ? 'hidden' : 'webkitHidden' in document ? 'webkitHidden' : ...

  9. 重写strcpy函数,以实现strcpy的功能

    char * strcpyTest(char *dst,const char *src);Action(){ char *ptr=(char*)malloc(100); char a[]={" ...

  10. html 获取和写入cookie的 方法

    //取Cookie的值            function getCookie(cookie_name) {     var allcookies = document.cookie;     v ...