码迷,mamicode.com
首页 > 其他好文 > 详细

二分查找方法

时间:2015-07-08 00:51:05      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:

问题描述:

二分查找指定的int数组


问题分析:

时间复杂度为O(logN)


代码实现:

package c02;

/**
 * @project: DataStructureAndAlgorithmAnalysis
 * @filename: BinarySearch
 * @version: 0.10
 * @author: Jimmy Han
 * @date: 22:57 2015/7/7
 * @comment: Test Purpose
 * @result:
 */
public class BinarySearch {
    public static void main(String[] args) {
        int[] a = {1, 2, 7, 9, 9, 12, 15, 24, 30};
        System.out.println(binarySearch(a, 7));
        System.out.println(binarySearch(a, 12, 1, 6));
    }

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

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

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

        return -1;
    }

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

        int mididx = (beginidx + endidx)/2;

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

    }
}


二分查找方法

标签:

原文地址:http://my.oschina.net/jimmyhan/blog/475863

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!