二分查找模板
package cn.ljm.arrays;
/**
* 测试二分法查找(折半查找)
* @author LJM
*/
import java.util.Arrays;
public class TestBinarySearch {
public static void main(String[] args) {
int [] array = {30, 20, 50, 10, 80, 9, 7, 12, 100, 40, 8};
Arrays.sort(array);//先排序
System.out.println(Arrays.toString(array));
System.out.println(binarySearch(array, 40));
}
//二分查找
public static int binarySearch(int [] array, int value) {
int low = 0;
int hight = array.length - 1;
while(low <= hight) {
int mid = (low + hight) / 2;
if(array[mid] == value) return mid;
else if(value < array[mid]) hight = mid - 1;
else low = mid + 1;
}
return -1;
}
}
b站来的集合