java实现二分法查找

public class TestBinsarySearch {
	int leftIndex = 0;
	int rightIndex = 0;
	int findVal = 0;
	
	public static int binarySearch(int[] arr,int leftIndex,int rightIndex,int findVal){
		
		if(leftIndex > rightIndex){
			return -1;
		}
		
		int midIndex = (leftIndex + rightIndex)/2;
		int midVal = arr[midIndex];
		
		if(findVal > midVal){
			return binarySearch(arr, midIndex+1, rightIndex, findVal);
		}else if(findVal < midVal){
			return binarySearch(arr,leftIndex,midIndex-1,findVal);
		}else {
			return midIndex;
		}
		
	}
	
	public static void main(String[] args) {
		int[] arr = {1,2,4,690,990};
		int findIndex = binarySearch(arr, 0, arr.length-1, 690);
		System.out.println("findIndex="+findIndex);
		System.out.println("findValue="+arr[findIndex]);
	}
}

 

你可能感兴趣的:(java实现)