Java10大经典算法,值得分享

https://www.cnblogs.com/ice-line/p/11753852.html
二分查找算法
/**

  • @desc 二分查询(非递归方式)
  • 案例:
  • {1,3,8,10,11,67,100},编程实现二分查找,要求使用非递归方式完成。
  • @Author xw
  • @Date 2019/9/27
    */
    public class BinarySearchNonRecursive {
    public static void main(String[] args) {
    int[] arr = {1, 3, 8, 10, 11, 67, 100};
    int index = binarySearch(arr, 1);
    if (index != -1) {
    System.out.println(“找到了,下标为:” + index);
    } else {
    System.out.println(“没有找到–”);
    }
    }
    private static int binarySearch(int[] arr, int target) {
    int left = 0;
    int right = arr.length - 1;
    while (left <= right) {
    int mid = (left + right) / 2;
    if (arr[mid] == target) {
    return mid;
    } else if (arr[mid] > target) {
    right = mid - 1; // 向左找
    } else {
    left = mid + 1; // 向右找
    }
    }
    return -1;
    }
    }
发布了33 篇原创文章 · 获赞 0 · 访问量 850

猜你喜欢

转载自blog.csdn.net/ninth_spring/article/details/104582591
今日推荐