递归和非递归两种方式实现二分法查找(java)

public class BinarySearch {
	
	public static void main(String[] args)
	{
		int[] arr = {1,3,5,7,9,11,13,15,17};
		System.out.println(search(arr,13));
		System.out.println(search1(arr,1,0,arr.length-1));
	}
	
	
	public static int search(int[] arr,int n)//非递归
	{
		int low = 0;
		int high = arr.length-1;
		while(low<=high)
		{
			int mid = (low+high)/2;
			if(arr[mid]==n)
				return mid;
			if(arr[mid]n)
			{
				high=mid-1;
			}
		}
		return -1;
		
	}
	public static int search1(int[] arr,int n,int begin,int end)//递归
	{
	
		
			int mid=(begin+end)/2;
			if(narr[end] || arr[begin]>arr[end])
			{
				return -1;
			}
			if(arr[mid]n)
			{
				return search1(arr,n,begin,mid-1);
			}
			else
				return mid;
	
	}

}

你可能感兴趣的:(java基础)