package com.example.algorithm; public class Bisection{ /** * @desc 二分法查找有序数组 O(logn) * @param arr 有序数组 * @param val 查找的值 * @return index 返回该值的索引位置 * */ public Integer searchByBisection(Integer[] arr ,int val){ int start = 0; int end = arr.length-1; while(start<=end){ int mid = (start+end); int item = arr[mid]; if(val==item) return mid; else if(val<item) end = mid-1; else if(val>item) start = mid+1; } return -1; } /** * @desc 简单查询查找有序数组 O(n) * @param arr 有序数组 * @param val 查找的值 * @return index 返回该值的索引位置 * */ public Integer searchBySimple(Integer[] arr ,int val){ if(arr!=null&&arr.length<0){ for(int i=0;i<arr.length;i++){ if(arr[i]==val) return i; } } return -1; } public static void main(String[] args) throws Exception{ Integer[] intArr = {1,2,3,4,5,6,7,8}; Bisection ds = new Bisection(); Integer mid = ds.searchByBisection(intArr,11); System.out.println(mid); } }