问题描述:
二分查找指定的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