边界控制
例:二分查找
普通查找:
从第一个开始,一个一个看
二分查找:
从中间开始看(效率高)
二分查找的必要条件:
Arr是一个有序数组
精确描述:
/**
* Searches element k in a sorted array.
*
* @param arr
* a sorted array
* @param k
* the element to search
* @return index in arr where k is. -1 if not found.
*/
Searches element k in a sorted array.
在排序数组中搜索元素k
the element to search
要搜索的元素
index in arr where k is.
K是数组中的索引【返回值返回下标】
-1 if not found
找不到返回-1
为什么b=m & 半开半闭区间的好处:
[a, b) + [b,c) = [a,c)
b - a = len([a, b))
- b-a=区间的长度
[a, a) ==> empty range
- 判断空
输出结果:
public static void main(String[] args)
{
BinarySearch bs = new BinarySearch();
System.out.println(bs.binarySearch(new int[] { 1, 2, 10, 15, 100 }, 15));
System.out.println(bs.binarySearch(new int[] { 1, 2, 10, 15, 100 }, -2));
System.out.println(bs.binarySearch(new int[] { 1, 2, 10, 15, 100 }, 101));
System.out.println(bs.binarySearch(new int[] { 1, 2, 10, 15, 100 }, 13));
System.out.println("=========");
System.out.println(bs.binarySearch(new int[] {}, 13));
System.out.println(bs.binarySearch(new int[] { 12 }, 13));
System.out.println(bs.binarySearch(new int[] { 13 }, 13));
System.out.println("=========");
System.out.println(bs.binarySearch(new int[] { 12, 13 }, 13));
System.out.println(bs.binarySearch(new int[] { 12, 13 }, 12));
}
大bug!!
【问题】a+b可能会溢出
当数组很大,a和b也很大的时候,相加溢出
【怎么处理】
【最好做法】
区间开头+区间长度/2
- (b-a)/2:区间长度/2
完整代码在这里哦!
CheeseCheese-IScream
给个小星星鼓励一下吧~❤谢谢❤