`
五月天
  • 浏览: 21134 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

java实现的折半查找

阅读更多
/**
 * 折半查找
 * author: zcl
 */
public class BinarySearch {

	public static int search(int[] arrays, int target) {
		
		int start = 0;
		int end = arrays.length - 1;
		int pos;
		while (start <= end) {
			pos = (start + end) / 2;
			if (arrays[pos] == target) {
				return pos;
			} else if (arrays[pos] > target) {//如果数组中间的数大于目标,则将end的位置变成数组中间位置-1的位置
				end = pos - 1;
			} else {
				start = pos + 1;//如果数组中间的数小于目标,则将start的位置变成数组中间位置+1的位置
			}
		} 
		return -1; //若没有查找到,则返回-1
	}
	
	public static void main(String[] args) {
		int[] arrays = {2,3,28,39,59,288,322,324,2323};
		System.out.println(search(arrays, 28));
		System.out.println(search(arrays, 322));
		System.out.println(search(arrays, 59));
		System.out.println(search(arrays, 288));
	}
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics