二分法查找的JAVA程序

二分法查找的JAVA程序
class HalfSearch 
{
	public static void main(String[] args) 
	{
		int []arr={11,15,18,45,65,77,81,91,98,105};
		printarr(arr);
		System.out.println();
		System.out.println("index = "+halfSearch(arr,81));
	}
	public static void printarr(int arr[])
	{
		for(int i=0;i<arr.length;i++)
			System.out.print(arr[i]+"\t");
	}
	public static int halfSearch(int arr[],int key)
	{
		int min,max,mid;
		min = 0;
		max =arr.length-1;
		while(min<=max)
		{
			mid=(min+max)>>1;
			if(key>arr[mid])
				min = mid+1;
			else if(key<arr[mid])
				max = mid-1;
			else 
				return mid;
		}
		return -1;
	}
}

你可能感兴趣的:(二分法查找的JAVA程序)