【算法】二分法查找
1 public class Main { 2 public static void main(String[] args) { 3 int[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,12}; 4 ArrayList<Integer> arrayList = new ArrayList<>(); 5 Arrays.sort(array); 6 7 int target = 11; 8 9 int beginLoc = 0; 10 int endLoc = array.length - 1; 11 12 while (endLoc > beginLoc) { 13 System.out.println(" beginLoc:" + beginLoc + "endLoc:" + endLoc); 14 if (array[(beginLoc + endLoc + 1) / 2] == target) { 15 System.out.println("ok"); 16 break; 17 } else if (array[(beginLoc + endLoc + 1) / 2] > target) { 18 endLoc = (beginLoc + endLoc + 1) / 2; 19 } else { 20 beginLoc = (beginLoc + endLoc + 1) / 2; 21 } 22 } 23 } 24 }
一定要注意,前后应该分别+1