Java 二分法查找

使用二分法进行查找,程序如下:

package cn.com.yy;

import java.util.Arrays;

/**
 * 二分法查找
 * @author Administrator
 *
 */
public class BinarySearchClient {

	public static void main(String[] args) {
		
		int[] arr = new int[]{4,5,2,1,8,3,0};
		Arrays.sort(arr); //数组进行排序
		int result = 4;
		int index = binarySearch(arr,result);
		System.out.println(index); //排序后的数组下标 4
	}
	
	/**
	 * 
	 * @param arr
	 * @param result
	 * @return 返回排序后的数组下标
	 * 
	 */
	public static int binarySearch(int[] arr, int result){
		
		int beginIndex = 0; //开始索引
		int endIndex = arr.length - 1; //结束索引
		int middleIndex = -1;    //默认的目标索引
		if(arr.length <1)
			return -1;
		if(result < arr[beginIndex] || result > arr[endIndex] || beginIndex > endIndex)
			return -1;
		while(beginIndex <= endIndex){
			middleIndex = (beginIndex + endIndex) >>> 1; //右移位运算符
			if(result < arr[middleIndex]){
				endIndex = middleIndex -1;
			}else if(result > arr[middleIndex]){
				beginIndex = middleIndex + 1;
			}else{
				return middleIndex ;
			}
		}
		return -1;
	}
}


你可能感兴趣的:(java,二分法,binarySearch,二分法查找)