• 一、二分查找法


    1.二分查找法(折半查找):减少查找序列的长度,分而治之地进行关键字的查找。

      优点是比较次数少,查找速度快,平均性能好,占用系统内存较少;

      缺点是要求待查表为有序表,且插入删除困难。

      因此,折半查找方法适用于不经常变动而查找频繁的有序列表。

      时间复杂度是 O(logn)

    2.代码实现: 

    package com.helq3.search;
    /**
     * 二分查找
     * @author Helena
     */
    public class binarySearch {
        
        //非递归方式执行的查询次数
        public static int times = 0;
        //递归方式执行的查询次数
        public static int times2 = 0;
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            int[] intarr = new int[]{1,2,4,6,9,16,32,56,66,74,89,95};//12= 2的4次方
                                //   0 1 2 3 4  5  6  7  8  9 10 11                        
            int index = binarySearch(intarr,74);
            System.out.println("times:"+times+",index:"+ index);
            int index2 = binarySearch2(intarr,0,intarr.length - 1,74);
            System.out.println("times:"+times2+",index:"+ index2);
    
        }
        /**
         * 非递归二分查找法
         * @param arr 有序数组
         * @param a 要查找的数值
         * @return
         */
        public static int binarySearch(int[] arr, int a){
            int high = arr.length - 1;
            int low = 0;
            while(low <= high){
                times ++ ;
                int mid = (low + high)/2;
                if(arr[mid]==a){
                    return mid;
                }else if(arr[mid] > a){
                    high = mid -1;
                }else{
                    low = mid + 1;
                }
            }
            
            return -1;
        }
        /**
         * 递归方式实现二分查找
         * @param arr 有序数组
         * @param low     
         * @param high
         * @param a 需要查找的值
         * @return
         */
        public static int binarySearch2(int[] arr,int low,int high,int a){
            if(low > high)
                return -1;
            int mid = (low + high)/2;
            times2++;
            if(arr[mid] == a){
                return mid;
            }else if(arr[mid] > a){
                high = mid -1;
                return binarySearch2(arr,low,high,a);
            }else{
                low = mid + 1;
                return binarySearch2(arr,low,high,a);
            }
        }
    
    }

    总结一句:好好学习,天天向上,此文借鉴了 https://www.cnblogs.com/xiexiandong/p/13057633.html,感谢博主。

  • 相关阅读:
    计算机考研复试真题 数字求和
    计算机考研复试真题 简单计算器
    计算机考研复试真题 N阶楼梯上楼问题
    P1082 [NOIP2012 提高组] 同余方程
    进制转换
    浮点数加法
    N的阶乘
    1055 The World's Richest (25 分)
    1028 List Sorting (25 分)
    1062 Talent and Virtue (25 分)
  • 原文地址:https://www.cnblogs.com/helq/p/13354561.html
Copyright © 2020-2023  润新知