image.png

    1. package com.atguigu.binarysearchnorecursion;
    2. /**
    3. * @author Dxkstart
    4. * @create 2022-04-11-19:28
    5. */
    6. public class BinarySearchNoRecur {
    7. public static void main(String[] args) {
    8. int[] arr = {1,3,8,10,11,67,100};
    9. int index = binarySearch(arr,11);
    10. System.out.println(index);
    11. }
    12. // 二分查找的非递归实现
    13. /**
    14. * @param arr 待查找的数组
    15. * @param target 需要查找的数
    16. * @return 返回对应的下标, -1表示没有找到
    17. */
    18. public static int binarySearch(int[] arr, int target) {
    19. int left = 0;
    20. int right = arr.length - 1;
    21. while (left <= right) {
    22. int mid = (left + right) / 2;
    23. if (arr[mid] == target) {
    24. return mid;
    25. } else if (arr[mid] > target) {
    26. // 向左查找
    27. right = mid - 1;
    28. } else {
    29. // 向右查找
    30. left = mid + 1;
    31. }
    32. }
    33. return -1;
    34. }
    35. }