java算法---二分查找

package com.shuobaotang.interview;

/**
 * 实现二分查找法
 * 给定一个有序的数组,和要查找的数字,如果查找成功
 * 返回数字在数组中的索引,否则返回-1
 * @author yangjianzhou
 *
 */
public class BinarySearch {
	
	public static int binarySearch(int [] intArray,int target){
		
		int high = intArray.length-1;
		int low = 0;
		int middle;
		while(low <= high){
			middle = (high+low)/2;
			if(target == intArray[middle]){
				return middle;
			}else if( target<intArray[middle]){
				high = middle - 1;
			}else{
				low = middle + 1;
			}
		}
		return -1;
	}
	
	public static void main(String[] args) {
		
		int [] aa = {1,2,3,4,5,6,7,8};
		System.out.println(binarySearch(aa,9));
		System.out.println(binarySearch(aa,2));
		System.out.println(binarySearch(aa,5));
	}
}



运行结果:
-1
1
4

你可能感兴趣的:(java算法)