public class BinarySearch {
public static void main(String[] args) {
int[] arr = {1,2,3,3,3,4,5,5,7};
int upper1 = floor_lower(arr, 3);
System.out.println(upper1);
}
//1.寻找第一个大于 target 的元素的下标,本案例中4 就是第一个大于 target 的元素 ,下标 = 5。
public static int upper(int[] arr,int target){
int left = 0;
int right = arr.length-1;
if(arr[right] <= target) return -1;
while (left < right) {
int mid = left + (right - left) / 2;
if (arr[mid] > target) {
//[l,mid,r]
right = mid;
} else if (arr[mid] == target) {
left = mid + 1;
} else {
left = mid + 1;
}
}
return left;
}
//2.如果数组中存在元素等于 target,则返回最后一个等于target 的元素下标,如果不存在,则返回第一个大于 target 的元素下标。本案例中最后一个等于target的下标 = 4。
public static int floor_upper(int[] arr,int target){
int left = 0;
int right = arr.length-1;
if(arr[right] < target) return -1;
while (left < right) {
int mid = left + (right - left) / 2;
if (arr[mid] > target) {
//[l,mid,r]
right = mid;
} else if (arr[mid] == target) {
left = mid + 1;
} else {
left = mid + 1;
}
}
if (left - 1 >= 0 && arr[left - 1] == target){
return left - 1;
}
return left;
}
//3.寻找最后一个小于 target 的元素的下标,本案例中 2 则是最后一个小于 target 的,下标 = 1.
public static int lower(int[] arr,int target){
int left = 0;
int right = arr.length - 1;
if(arr[left] >= target) return -1;
while (left < right){
int mid = left+(right-left+1)/2;
if (arr[mid] < target){
left = mid;
}else if(arr[mid] == target){
right = mid - 1;
}else {
right = mid - 1;
}
}
return right;
}
//4.如果数组中存在元素等于 target,则返回第一个等于target 的下标,如果不存在,则返回最后一个小于 target 的元素的下标。本案例中第一个等于target的下标 = 2。
public static int floor_lower(int[] arr,int target){
int left = 0;
int right = arr.length - 1;
if(arr[left] > target) return -1;
while (left < right){
int mid = left+(right-left+1)/2;
if (arr[mid] < target){
left = mid;
}else if(arr[mid] == target){
right = mid - 1;
}else {
right = mid - 1;
}
}
if (right + 1 < arr.length && arr[right + 1] == target) return right + 1;
return right;
}
}