二分查找的前提是:你得先排好序,但是排序问题不在讨论。
直接上代码:
import java.util.Optional; public class MyArray { public static void main(String[]args) { int[] arr = new int[]{1,2,3}; for (int i = 0; i < arr.length; i++) { System.out.println("arr[" + i + "]=" + arr[i]); } Optional<Integer> num = searchByHalf(arr, 2); if (num.isPresent()) { System.out.println(num.get()); } else { System.out.println("not find"); } } public static Optional<Integer> searchByHalf(int[] arr, int target) { int low = 1; int high = arr.length; while (low <= high) { int middle = (low+high)/2; if (arr[middle - 1] == target) { return Optional.of(middle); } else if (arr[middle - 1] < target) { low = middle+1; } else if (arr[middle - 1] > target) { high = middle-1; } } return Optional.ofNullable(null); } }
java8 出来了,有很多新的东西,optional就是其中一个,试着用一用。