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

    正文

      中午闲着有点时间,做个demo睡觉去,这个例子网上应该都有,自己只是敲一下给自己做个记录。

      

      public static void main(String[] args) {

        int[] whitelist = new int[]{12,13,34,56,78,88,99,100};
        Arrays.sort(whitelist);
        Scanner sc = new Scanner(System.in);

        boolean go=true;
        while(true)
        {
          System.out.println("请输入要查找的数");
          int nextInt = sc.nextInt();

          sc.nextLine();
          int result = rank(nextInt,whitelist);
          if(result!=-1)
          {
            System.out.println("找到的数字位置为:"+result);
            go=false;
          }
          else
          {
            System.out.println("没有找到输入的数字位置");
          }
          }
          }

          public static int rank(int key, int[] a) {
            // 数组必须是有序的
            int lo = 0;
            int hi = a.length - 1;
            while (lo <= hi) {
            // 被查找的键要么不存在,要么必然存在于a[lo,hi]之间
            int mid = lo + (hi - lo) / 2;
            if (key < a[mid]) {
            hi = mid - 1;
            } else if (key > a[mid]) {
              lo = mid + 1;
            } else {
              return mid;
          }

        }

        return -1;
      }

  • 相关阅读:
    git commit 合并
    git 管理 Linux 文件系统
    python 全局变量的使用
    JavaScript 中 类型转换
    canconfig 配置命令
    python 调用 shell 命令
    python 3 操作mysql数据库的方法
    python 字符串和整数,浮点型互相转换
    JavaScript 里面的整数 位 操作
    JavaScript 使用 php 的变量
  • 原文地址:https://www.cnblogs.com/hackerxiaoyon/p/7560889.html
Copyright © 2011-2022 走看看