一、二分查找
1.定义
二分查找也称折半查找(Binary Search),它是一种效率较高的查找方法。
2.查找过程
首先,假设表中元素是按升序排列,将表中间位置记录的关键字与查找关键字比较,如果两者相等,则查找成功;否则利用中间位置记录将表分成前、后两个子表,如果中间位置记录的关键字大于查找关键字,则进一步查找前一子表,否则进一步查找后一子表。重复以上过程,直到找到满足条件的记录,使查找成功,或直到子表不存在为止,此时查找不成功。
二、二分查找的实现
1.基础版
//基础版 public static int binarySearchBasic(int[] a,int target){ int i=0,j=a.length-1; //设置指针的初值 while (i<=j){ //i~j里面有东西 int m=(i+j)>>>1; //解决溢出问题,等同于m=(i+j)/2 if (target<a[m]){ //目标在左边 j=m-1; }else if (a[m]<target){ //目标在右边边 i=m+1; }else { //找到了 return m; } } return -1; //找不到 }
2.改动版
//改动版:右边的指针作为边界 public static int binarySearchGaidong(int[] a,int target){ int i=0,j=a.length; //第一处改动 while (i<j){ //第二处 int m=(i+j)>>>1; if (target<a[m]){ j=m; //第三处 }else if (a[m]<target){ i=m+1; }else { return m; } } return -1; }
3.平衡版
//平衡版:先缩小范围再比较 public static int binarySearchBalance(int[] a,int target){ int i=0,j=a.length; while (1<j-i){ int m=(i+j)>>>1; if (target<a[m]){ j=m; }else { i=m; } } if (target==a[i]){ return i; }else { return -1; } }
4.Java版
//用Arrays里面的方法 Arrays.binarySearch(a,2)
binarySearch方法:
两个参数:a-->要查找的数组
key-->要查找的值
返回值:
找到了:返回索引值
找不到:返回 -(插入点-1)
插入点:就是假如要将target插入数组对应的索引值
5.Leftmost版
//有重复返回最左边的索引 public static int binarySearchLeftmost(int[] a,int target){ int i=0,j=a.length-1; int candidate=-1; //候选值 while (i<=j){ int m=(i+j)>>>1; if (target<a[m]){ j=m-1; }else if (a[m]<target){ i=m+1; }else { candidate=m; j=m-1; } } return candidate; }
6.Rightmost版
//有重复返回最右边的索引 public static int binarySearchRightmost(int[] a,int target){ int i=0,j=a.length-1; int candidate=-1; //候选值 while (i<=j){ int m=(i+j)>>>1; if (target<a[m]){ j=m-1; }else if (a[m]<target){ i=m+1; }else { candidate=m; i=m+1; } } return candidate; }
7.Leftmost2版
//返回大于等于target的最靠左的索引 public static int binarySearchLeftmost2(int[] a,int target){ int i=0,j=a.length-1; while (i<=j){ int m=(i+j)>>>1; if (target<=a[m]){ j=m-1; }else { i=m+1; } } return i; }
8.Rightmost2版
//返回小于等于target且最靠右的位置 public static int binarySearchRightmost2(int[] a,int target){ int i=0,j=a.length-1; while (i<=j){ int m=(i+j)>>>1; if (target<a[m]){ j=m-1; }else { i=m+1; } } return i-1; }