package com.xulu.algorithm.binarysearch;
/**
* @Title: BinarySearchLeftMost
* @Author xulu
* @Package com.xulu.algorithm.binarysearch
* @Date 2023/4/26 19:31
*/
public class BinarySearchExpansion {
public static void main(String[] args) {
//1.定义一个数组
int[] arr={1,3,5,5,5,8,9};
//2.查找排名,索引从0开始,需要加1
System.out.println(binarySearchLeftMost(arr, 5) +1);//3
System.out.println(binarySearchLeftMost(arr, 9) +1);//7
//3.查找前任,该索引-1就是其前任
System.out.println(binarySearchLeftMost(arr, 5)-1); //1
System.out.println(binarySearchLeftMost(arr, 8)-1); //4
//4.查找后任,该索引+1就是其后任
System.out.println(binarySearchRightMost(arr,5)+1); //5
System.out.println(binarySearchRightMost(arr,8)+1); //6
//5.求范围
//5.1.x<5[0,binarySearchLeftMost(5)-1]
//5.2.x<=5,[0,binarySearchRightMost(5)]
//5.3.x>5 [binarySearchRightMost(5)+1,数组的最大范围]
//5.4.x>=5 [binarySearchLeftMost(5),数组的最大范围]
//5.5 5<x<9 [binarySearchRightMost(5)+1,binarySearchLeftMost(9)-1]
//5.6 5<=x<=9 [binarySearchLeftMost(5),binarySearchRightMost(9)]
}
public static int binarySearchLeftMost(int[] arr,int target){
//1.设置指针和初始值
int i=0,j=arr.length-1;
//2.只要在这个范围内就有值可查
while (i<=j){
//3.确定中间索引mid
int mid=(i+j)/2;
//4.目标值小于等于中间值,往左找
if (target<=arr[mid]){
j=mid-1;
}else {
i=mid+1;
}
}
//5.存在返回索引,不存在返回大于等于目标值的最靠左索引
return i;
}
public static int binarySearchRightMost(int[] arr, int target) {
//1.设置指针和初始值
int i = 0, j = arr.length - 1;
//2.只要在这个范围内就有值可查
while (i <= j) {
//3.确定中间索引mid
int mid = (i + j) / 2;
//4.目标值大于等于中间值,往右找
if (target >= arr[mid]) {
i = mid + 1;
} else {
j = mid - 1;
}
}
//5.存在返回索引,不存在返回大于等于目标值的最靠右索引
return i-1;
}
}
这些就是对二分查找的一些拓展了。