zoukankan      html  css  js  c++  java
  • Java二分法

    public class Dichotomy {
        
        //定义查找次数
        static int count = 0;
        
        public static void main(String[] args) {
            
            //定义数组
            int [] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
            
            //二分法查找
            int result = searchRecursive( array, 0, array.length - 1, 3);
            
            //打印结果
            System.out.println("二分法查找结果为=" + result);
            System.out.println("查找次数为=" + count);
        }
        
        /**
         * 执行递归二分查找,返回第一次出现该值的位置
         *
         * @param array
         *            已排序的数组
         * @param start
         *            开始位置
         * @param end
         *            结束位置
         * @param findValue
         *            需要找的值
         * @return 值在数组中的位置,从0开始。找不到返回-1
         */
        private static int searchRecursive(int[] array, int start, int end, int findValue) {
            
            //数组如果为空则返回-1
            if(array == null){
                
                return -1;
            }
            
            
            
            while(start <= end){
                
                count++;
                
                //获取中间位置
                int middle = (start + end) / 2;
                
                //获取中间值
                int middleValue = array[middle];
                
                if(middleValue == findValue){
                    
                    return middle;
                }else if(findValue < middleValue){
                    
                    end = middle - 1;
                }else{
                    
                    start = middle + 1;
                }
                
            }
            
            return -1;
        }
    }

  • 相关阅读:
    ISP基础(01):ISP模块列表
    Linux 开发(02):打印特殊含义转义符
    note template
    apply、call、bind的区别
    Fiddle 抓包工具
    post和get的使用场景和区别
    闭包
    原型链
    node.js
    CSS垂直居中
  • 原文地址:https://www.cnblogs.com/gslblog/p/6888327.html
Copyright © 2011-2022 走看看