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

  • 相关阅读:
    Libevent库学习笔记
    最大的k个数问题
    MongoDB之整库备份还原单表collection备份还原
    精通MATLAB混合编程
    AutoCAD 2016中文版从入门到精通(第2版)
    MATLAB科学计算范例实战速查宝典
    Android系统应用开发实战详解
    AutoCAD快捷命令速查大全
    TCP IP入门经典(第5版)
    STC8系列单片机开发指南:面向处理器、程序设计和操作系统的分析与应用
  • 原文地址:https://www.cnblogs.com/hackerxiaoyon/p/7560889.html
Copyright © 2011-2022 走看看