zoukankan      html  css  js  c++  java
  • 二分查找

    一、概念(复杂度O(㏒₂n))

    二分查找也称折半查找(Binary Search),它是一种效率较高的查找方法,可以理解为一直对折。但是,折半查找要求线性表必须采用顺序存储结构(优点:随机存取表中元素、储存密度大。缺点:插入和删除操作需要移动元素。),而且表中元素按关键字有序排列。 

    二、要求

    1.必须采用顺序存储结构
    2.必须按关键字大小有序排列。
     
    三、代码
     
    /**
    * @author 作者 ki16:
    * @version 创建时间:2021年5月12日 下午5:26:05
    *
    */
     
    public class DichotomyAlgorithm {
    public static void main(String[] args) {
    //测试
    int[] arr = {1, 2, 3, 4, 5, 8, 10, 11, 67, 100};
    int index = binarySearch (arr, 10);
    System.out.println ("index=" + index);
    }
     
    // 二分查找
    public 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;
    }
     
    }
     

  • 相关阅读:
    线程的等待与唤醒
    多线程start()与run()的区别
    Thread与Runnable
    关于i++和++i的一些见解
    Mysql优化(转)
    Java 注解
    Java 泛型(转)
    Java 中的CAS
    CAS ABA问题
    Java 线程池分析
  • 原文地址:https://www.cnblogs.com/ki16/p/14760868.html
Copyright © 2011-2022 走看看