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

    public class BinarySearch {
        public static void main(String[] args) {
            int[] arr = {10, 20, 30, 40, 50, 60, 70, 80, 90};
            int num = 70;
    
            System.out.println(binarySearchMethods(num, arr));
        }
    
        /**
         * arr必须为排序后的数组
         */
        public static int binarySearchMethods(int num, int[] arr) {
            int minindex = 0;
            int maxindex = arr.length;
            while (true) {
                if (minindex == maxindex) {
                    return (minindex + maxindex) / 2;
                } else {
                    if (num < arr[(minindex + maxindex) / 2]) {
                        maxindex = (minindex + maxindex) / 2 - 1;
                    } else if (arr[(minindex + maxindex) / 2] < num) {
                        minindex = (minindex + maxindex) / 2 + 1;
                    } else {
                        return (minindex + maxindex) / 2;
                    }
                }
            }
        }
    }
  • 相关阅读:
    CodeForces
    CodeForces
    AtCoder
    AtCoder
    CodeForces
    CodeForces
    CodeForces
    CodeForces
    Centos7配置yum国内镜像及仓库升级
    环境变量
  • 原文地址:https://www.cnblogs.com/linding/p/13489888.html
Copyright © 2011-2022 走看看