「算法与数据结构」查找算法
二分查找
1public class BinarySearch{
2 public static void main(String[] args) {
3 int[] arr = {1,2,3,4,5,6,7,8};
4 int k = 8;
5 System.out.println(binarySerach(arr, k));
6 }
7
8 public static int binarySerach(int[] arr, int k){
9 int a = 0;
10 int b = arr.length;
11
12 while(a < b){
13 int mid = a+(b-a)/2;
14 if(k < arr[mid]){
15 b = mid;
16 }else if(k > arr[mid]){
17 a = mid + 1;
18 }else{
19 return mid;
20 }
21 }
22 return -1;
23
24 }
25}