二分查找方法

本文介绍了一种高效的搜索算法——二分查找,并提供了两种不同的实现方式:迭代和递归。通过具体的Java代码示例展示了如何在有序数组中查找指定元素。

问题描述:

二分查找指定的有序数组


问题分析:

时间复杂度为O(logN)


代码实现:

package c02;

import java.util.Comparator;

/**
 * @project: DataStructureAndAlgorithmAnalysis
 * @filename: BinarySearch
 * @version: 0.10
 *           0.20 use generic
 * @author: Jimmy Han
 * @date: 22:57 2015/7/7
 *        21:33 2015/09/29
 * @comment: Test Purpose
 * @result:
 */
public class BinarySearch<AnyType> {
    public static final int NOT_FOUND = -1;

    public static void main(String[] args) {
        Integer[] a = {1, 2, 7, 9, 9, 12, 15, 24, 30};
        System.out.println(binarySearch(a, 7));
        System.out.println(binarySearch(a, 7, 1, 6));
    }

    /**
     * Performs the standard binary search. Normal
     * @return index where item is found, or -1 if not found
     */
    public static <AnyType extends Comparable<? super AnyType>>
    int binarySearch(AnyType[] a, AnyType x){
        int low = 0, high = a.length - 1;

        while(low <= high){
            int mid = (low + high)/2;

            if(a[mid].compareTo(x) < 0)
                low = mid + 1;
            else if(a[mid].compareTo(x) > 0)
                high = mid - 1;
            else
                return mid;
        }

        return NOT_FOUND;
    }

    /**
     * Performs the standard binary search. Recursively.
     * @return index where item is found, or -1 if not found
     */
    public static <AnyType extends Comparable<? super AnyType>>
    int binarySearch(AnyType[] a, AnyType x, int beginidx, int endidx){
        if(a[beginidx].compareTo(x) > 0 || a[endidx].compareTo(x) < 0)
            return -1;

        int mididx = (beginidx + endidx)/2;

        if(a[mididx].compareTo(x) < 0)
            return binarySearch(a, x, mididx + 1, endidx);
        else if(a[mididx].compareTo(x) > 0)
            return binarySearch(a, x, beginidx, mididx - 1);
        else
            return mididx;

    }
}


转载于:https://my.oschina.net/jimmyhan/blog/475863

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值