二分查找

二分查找


给定任意排序整型数组,通过二分查找算法,找到目标值在数组中的索引位置,如果不存在则返回 -1。

这个算法的复杂度为 \(O(LgN)\)

 1/**
 2 * 2分查找
 3 *
 4 * @author wangy
 5 * @version 1.0
 6 * @date 2020/6/5 / 14:23
 7 */
 8public class BinarySearch {
 9
10    public static int find(int[] arr, int key) {
11        int low = 0;
12        int high = arr.length - 1;
13
14        while (low <= high) {
15            int mid = (low + high) / 2;
16            if (arr[mid] > key) {
17                high = mid - 1;
18            } else if (arr[mid] < key) {
19                low = mid + 1;
20            } else {
21                return mid;
22            }
23        }
24        return -1;
25    }
26
27    public static void main(String[] args) {
28       int[] ints = {6,12,14,25,33,43,51,53,64,72,84,93,95,96,99};
29        int i = BinarySearch.find(ints, 33);
30        System.out.println(i);
31    }
32}