有序数组的二分查找

有序数组二分查找的基本原理:因为数组是有序的,先找到中间位置的值,如果目标比这个值大,那么该目标必定在数组的右半部分,以此循环或者递归,一直找到这个数值为止。此算法的时间复杂度为O(logN),N为数组的长度

 

 

package algorithm.arrayfind;

public class SortedArrayBinarySearch {
    
    public static void main(String[] args) {
        int[] source=new int[]{1,3,5,7,9,12};
        int key = 12;
        System.out.println(binaryRecurSearch(source, key));;
        System.out.println(binarySearchLoop(source, key));;
    }
    
    public static int binaryRecurSearch(int[] source, int key){
        return binarySearchRecursive(source, key,0,source.length-1);
    }
    
    private static int binarySearchRecursive(int[] source, int key,int beginIndex,int endIndex){
        int midIndex = (beginIndex+endIndex)/2;
        if(key<source[beginIndex]||key>source[endIndex]||beginIndex>endIndex){  
            return -1;  
        }  
        System.out.println("=======");
        if(key == source[midIndex]){
            return midIndex;
        }else if(key > source[midIndex]){
            return binarySearchRecursive(source, key, midIndex+1, endIndex);
        }else{
            return binarySearchRecursive(source, key, beginIndex, midIndex-1);
        }
        
    }
    
    public static int binarySearchLoop(int[] source, int key){
        int beginIndex = 0;
        int endIndex = source.length-1;
        
        
        while(true){
            System.out.println("=======");
            if(key<source[beginIndex]||key>source[endIndex]||beginIndex>endIndex){  
                return -1;  
            }  
            int midIndex = (beginIndex+endIndex)/2;
            if(key == source[midIndex]){
                return midIndex;
            }else if(key > source[midIndex]){
                beginIndex = midIndex +1;
            }else{
                endIndex = midIndex -1;
            }
        }
        
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值