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;
      }

  • 相关阅读:
    多列布局之等分布局
    布局之不定宽与自适应
    多列布局之一列、多列定宽及一列自适应布局
    居中布局之水平垂直布局
    JQuery 学习记录
    初遇GitHub
    关于JS中的函数定义及函数表达式
    类型识别
    页面制作(PS/HTML/CSS)易错点总结
    工欲善其事必先利其器系列之:更换Visual Studio代码风格.
  • 原文地址:https://www.cnblogs.com/hackerxiaoyon/p/7560889.html
Copyright © 2011-2022 走看看