二分查找法

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));
		
		
	}
}
 

你可能感兴趣的:(java)