java 二分搜索法

package search;
import java.util.Random;
/**
 * 二分搜索法
 * @author e421083458
 */
public class BinarySearch {
	public static void main(String args[]){
		Random ran = new Random();
		int sort[] = new int[10];
		for(int i=0;i<sort.length;i++){
			sort[i] = ran.nextInt(10);	
		}
		int mask = binarySearch(sort,6);
		System.out.println(mask);
	}
    /**  
     * 二分搜索法,返回座标,不存在返回-1  
     * @param sort  
     * @return  
     */
	public static int binarySearch(int[] sort,int data){
		if(data<sort[0] || data>sort[sort.length-1]){
			return -1;			
		}
		int begin = 0;
		int end = sort.length;
		int mid = (begin+end)/2;
		while(begin<=end){
			mid = (begin+end)/2;
			if(data > sort[mid]){
				begin = mid+1;				
			}else if(data < sort[mid]){
				end = mid - 1;				
			}else{
				return mid;			
			}
		}
		return -1;
	}
}

你可能感兴趣的:(java 二分搜索法)