`
zhengjiong
  • 浏览: 69118 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

二分查找法

    博客分类:
  • Java
阅读更多

package com.zj.exercise;

import java.util.Arrays;
/**
 * use:二分查找法
 * @author zhengjiong
 * time:2011-9-13 下午05:40:30
 */
public class BinarySearch {
	
	public static int search(int[] a, int value){
		int start = 0;
		int end = a.length - 1;
		int middle;
		
		while(start <= end){
			
			middle = (start + end) / 2;
			
			if(a[middle] == value){
				return middle;
			}else if(a[middle] < value){
				start = middle + 1;
			}else if(a[middle] > value){
				end = middle - 1;
			}
		}
		
		return -1;
	}
	
	
	public static void main(String[] args){
		
		int[] a = new int[]{3, 6, 1, 13 ,11 ,17};
		Arrays.sort(a);
		
		System.out.println(BinarySearch.search(a, 3));
		
		
	}
}
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics