思路分析
    1.对升序数组进行查找,查找具体的值所对应的索引
    2.取中间索引跟目标值进行比较,
    (1)如果目标值=中间值,则返回中间值索引;
    (2)如果目标值>中间值,则左边索引为中间索引+1;
    (3)如果目标值<中间值,则右边索引为中间索引-1;
    左侧<=右侧索引时进行以上处理,否则就是没有找到返回-1

    1. public class BinarySearch {
    2. /**
    3. * 二分查找(非递归)
    4. * @return
    5. */
    6. public static int search(int[] arr, int value) {
    7. int left = 0;
    8. int right = arr.length - 1;
    9. while (left <= right) {
    10. int mid = (left + right) / 2;
    11. if (arr[mid] == value) {
    12. return mid;
    13. } else if (value < arr[mid]) {
    14. right = mid - 1;
    15. } else {
    16. left = mid + 1;
    17. }
    18. }
    19. return -1;
    20. }
    21. public static void main(String[] args) {
    22. int[] arr = new int[]{1, 3, 5, 6, 7, 8, 10};
    23. int index = search(arr, 7);
    24. System.out.println("二分查找(非递归):" + index);
    25. }
    26. }