折半查找JAVA语言描述

public class halfsearch {
	
	private static final int NOT_FOUND = -1;
	
	public static <AnyType extends Comparable<? super AnyType>>
		int binarySearch(AnyType[] a,AnyType x){
		//DEFINE FIRST INDEX AND LAST INDEX
		int low=0,high=a.length-1;
		//WHILE LOW POINTER AT THE FRONT OF THE HIGH POINTER
		while(low <= high){	
			int mid = (low + high) / 2;
			//x > a[mid]
			if(a[mid].compareTo(x)<0)
				low = mid + 1;
			//x < a[mid]
			else if(a[mid].compareTo(x)>0)
				high = mid -1;
			//FOUND
			else 
				return mid;	
		}	
		return NOT_FOUND;
	}
	public static <AnyType extends Comparable<? super AnyType>> void main(String[] args){
		Integer[] a={1,2,3,4,5,6,7,8,9};
		Integer  x =6;
		System.out.println(binarySearch(a, x));
	}
}

 

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