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

    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;

      }
    }

  • 相关阅读:
    1 . CentOS 7的yum更换为国内的阿里云yum源
    0. vagrant+vbox创建centos7虚拟机
    git上传到码云和下载到本地
    spring boot udp或者tcp接收数据
    你好,博客园
    使用firdder抓取APP的包
    初见loadrunner
    sublime快捷键大全
    html中行内元素与块级元素的区别。
    html.css溢出
  • 原文地址:https://www.cnblogs.com/hwgok/p/5356298.html
Copyright © 2011-2022 走看看