• 二分法查找


    public class BinarySearch {
      public static void main(String[] args) {
        int[] arr = {234,245,77,3,543,67,78,95,378,678,205,753,457,2903,340};
        int searchWord = 1150;//要查找的数
        System.out.println("普通循环查找"+searchWord+" 用的次数是"+generalLoop(arr, searchWord));
        System.out.println("二分法查找"+searchWord+" 用的次数是"+binarySearch(arr, searchWord));
      }
      //普通循环法,最少需要比较一次,比如查找1,最多需要比较15次,比如8721
      static int generalLoop(int[] arr,int searchWord){
        int searchCount = 0;
        for(int i=0;i<arr.length;i++){
          searchCount++;
          if(searchWord==arr[i]){
            break;
          }
        }
        return searchCount;
      }
      //二分法查找
      static int binarySearch(int[] arr,int searchWord){
        Arrays.sort(arr);//先对传进来的数组进行排序
        int iIndex = 0;//相当于指针的变量
        int iStart = 0;
        int iEnd = arr.length-1;
        int searchCount = 0; //循环次数的统计
        for(int i=0;i<arr.length/2;i++){
          searchCount++;
          iIndex = (iStart+iEnd)/2;
          if(arr[iIndex]<searchWord){
            iStart = iIndex;
          }else if(arr[iIndex]>searchWord){
            iEnd = iIndex;
          }else {
            break;
          }
        }
        return searchCount;

      }
    }

  • 相关阅读:
    给Lisp程序员的Python简介
    QuickLisp常用命令
    修改windows cmd字体
    Eclipse生成JavaDoc时指定字符集, 避免页面乱码
    css颜色名
    css3动画
    使用placeholder实现动态配置persistence.xml
    spring下配置tomcat jdbc pool 报找不到"com.mysql.jdbc.Driver"类
    去除移动端浏览器点击元素时的边框
    JS经典闭包问题
  • 原文地址:https://www.cnblogs.com/hwgok/p/5356298.html
Copyright © 2020-2023  润新知