• Java实现二分查找(折半查找)


    1 问题描述
    首先,了解一下何为折半查找?此处,借用《算法设计与分析基础》第三版上一段文字介绍:

    在这里插入图片描述

    2 解决方案
    2.1 递归法

    package com.liuzhen.chapter4;
    
    public class BinarySearch {
        //方法1:递归求解
        public void recursionSearch(int[] A,int start,int end,int number){
            int mid = (start + end)/2;
            if(A[mid] == number)
                System.out.println("使用递归法求取number = "+number+"的数组下标结果:"+mid);
            if(A[mid] > number)
                recursionSearch(A,start,mid-1,number);   //递归调用
            if(A[mid] < number)
                recursionSearch(A,mid+1,end,number);     //递归调用
        }
        
        
        public static void main(String[] args){
            BinarySearch test = new BinarySearch();
            int[] A = {3,14,27,31,39,42,55,70,74,81,85,93,98};
            test.recursionSearch(A, 0, A.length-1, 70);
        }
    }
    

    运行结果:

    使用递归法求取number = 70的数组下标结果:7
    

    2.2 迭代法

    package com.liuzhen.chapter4;
    
    public class BinarySearch {
        
        //方法2:迭代求解
        public int iterationSearch(int[] A,int number){
            int start = 0;
            int end = A.length-1;
            while(start <= end){
                int mid = (start + end)/2;
                if(A[mid] == number)
                    return mid;
                if(A[mid] > number)
                    end = mid-1;
                if(A[mid] < number)
                    start = mid+1;
            }
            return -1;
        }
        
        public static void main(String[] args){
            BinarySearch test = new BinarySearch();
            int[] A = {3,14,27,31,39,42,55,70,74,81,85,93,98};
            System.out.println("使用迭代法求解number = 70的数组下标结果:"+test.iterationSearch(A, 70));
        }
    }
    

    运行结果:

    使用迭代法求解number = 70的数组下标结果:7
    
  • 相关阅读:
    P3350 [ZJOI2016]旅行者
    P4178 Tree
    P2375 [NOI2014]动物园
    P2827 蚯蚓
    1002: [FJOI2007]轮状病毒
    1070: [SCOI2007]修车
    AtCoder Grand Contest 021完整题解
    Running to the End(Codeforces & AtCoder 百套计划)
    SDWC2017游记
    非传统题初探——AtCoder Practice Contest #B
  • 原文地址:https://www.cnblogs.com/a1439775520/p/13077982.html
Copyright © 2020-2023  润新知