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

修改版

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. vuex初使用(写的当然是最简单的应用啦)

    关于vuex的简图 vuex文档:https://vuex.vuejs.org/zh-cn/installation.html 一:npm安装 npm install vuex --save 在mai ...

  2. HDU-1269-迷宫城堡(强连通 模板)

    链接:https://vjudge.net/problem/HDU-1269 题意: 为了训练小希的方向感,Gardon建立了一座大城堡,里面有N个房间(N<=10000)和M条通道(M< ...

  3. 后台任务利器之Hangfire

    后台任务利器之Hangfire 一.简述 Hangfire作为一款高人气且容易上手的分布式后台执行服务,支持多种数据库.在.net core的环境中,由Core自带的DI管理着生命周期,免去了在NF4 ...

  4. 使用Zeppelin时出现sh interpreter not found错误的解决办法(图文详解)

    不多说,直接上干货! 问题详解 http://192.168.80.145:8099/#/notebook/2CSV2VT5S 相关博客是 Zeppelin的入门使用系列之使用Zeppelin运行sh ...

  5. docker系列(二):镜像

    1 引言 将docker与汽车生产线类比,如果说docker引擎是汽车生产车间,那么容器就是最终的产品——汽车,而本节要介绍的镜像就如同汽车设计图纸,其重要性不言而喻——只有有了设计图(镜像),才能生 ...

  6. 【踩坑】List 的陷阱

    今天测试iReview项目数据的反馈,发现有些语句总无法执行. 经过调试排查后,发现List<自定义类>返回了空集"[]",却无法进入if语句里面,即 if (List ...

  7. 在使用seek()函数时,有时候会报错为 “io.UnsupportedOperation: can't do nonzero cur-relative seeks”,代码如下:

    __author__ = 'ZHHT' #!/usr/bin/env python # -*- coding:utf-8 -*- import os f = open("test1" ...

  8. BFC(块级 格式化上下文)的理解

    本文转载(https://segmentfault.com/a/1190000013647777) 一.BFC的概念 1.规范解释 块格式化上下文(Block Formatting Context,B ...

  9. display:inline-block间隙产生的原因以及解决方案

    display-inline-block是让元素在一行显示,但是这些元素在html里面是上下行排列的,所以中间有换行符,于是并排显示就有了换行符带来的空隙.那么如何解决呢? 方案一:将html标签要d ...

  10. Wireshark漫谈(一)

    可能有人会说,一个软件的安装有什么好谈的,无非就是"同意,同意,同意......是,是,是"诸如此类的选项.的确,Wireshark软件的安装步骤是挺简单的,不过本文不是想谈安装步 ...