文章目录
必须是有序的序列,才可以使用二分法
三要素:左下标、mid、右下标
二分法四种模板
int[] arr = {1,2,3,4,5,5,5,6,7,8,9};
具体情况,具体调试,不要死记硬背
找左边第一个
- mid = (le + re) >> 1
- le = mid + 1
- re = mid
找左边最后一个
- mid = (le + re + 1) >> 1
- le = mid
- re = mid - 1
package ch04.bisection;
/**
* @author Dylan
* @date 2020/5/2 - 17:14
*/
public class Template {
public static void main(String[] args) {
int[] arr = {1,2,3,4,5,5,5,6,7,8,9};
System.out.println(binarySearch1(arr, 5)); // 7
System.out.println(binarySearch2(arr, 5)); // 4
System.out.println(binarySearch3(arr, 5)); // 6
System.out.println(binarySearch4(arr, 5)); // 3
}
// 找到第一个大于x的下标
public static int binarySearch1(int[] arr, int x){
int le = 0, re = arr.length - 1;
while(le < re){
int mid = (le + re) >> 1;
if(arr[mid] <= x) le = mid + 1;
else re = mid;
}
return le;
}
// 找到左边第一个等于x的下标
public static int binarySearch2(int[] arr, int x){
int le = 0, re = arr.length - 1;
while(le < re){
int mid = (le + re) >> 1;
if(arr[mid] < x) le = mid + 1;
else re = mid;
}
return le;
}
//找到左边最后一个等于x的下标
public static int binarySearch3(int[] arr, int x){
int le = 0, re = arr.length - 1;
while(le < re){
int mid = (le + re + 1) >> 1;
if(arr[mid] <= x) le = mid;
else re = mid - 1;
}
return le;
}
//找到左边第一个小于x的下标
public static int binarySearch4(int[] arr, int x){
int le = 0, re = arr.length - 1;
while(le < re){
int mid = (le + re + 1) >> 1;
if(arr[mid] < x) le = mid;
else re = mid - 1;
}
return le;
}
}