二分查找算法,循环和递归两种方式

package indi.tom.algorithm.search;

import org.junit.Test;

/**
 * @Author: Tom
 * @Date: 2021年1月7日 下午5:26:29
 * @Version: 1.0
 * @Description: two implement of binary search: look and recursion
 */
public class BinarySearch {

	@Test
	public void test01() {
		int[] array = {0,1,2,3,4,5,6,7,8,9,10};
		System.out.println(searchWithLoop(array, 6));
		System.out.println(searchRecursively(array, 6, 0, 9));
	}

	/**
	 * 
	 * @Description: use loop to search 
	 * @param 
	 * @return -1 if not found, the index of target otherwise. 
	 * @throws
	 */
	private int searchWithLoop(int[] array, int target) {
		if (null == array || array.length == 0)
			throw new IllegalArgumentException("The given array can't be null or 0 length size");
		int left = 0;
		int right = array.length;
		int mid = (left + right) / 2;
		while (left <= right) {
			if (target == array[mid]) {
				return mid;
			} else if (target > array[mid]) {
				left = mid;
				left++;
			} else if (target < array[mid]) {
				right = mid;
				right--;
			}
			mid = (left + right) / 2;
		}
		return -1;
	}
	
	private int searchRecursively(int[] array, int target, int left, int right) {
		if (null == array || array.length == 0)
			throw new IllegalArgumentException("The given array can't be null or 0 length size");
		if(left > right) return -1;
		int mid = (left + right) / 2;
		
		if(target == array[mid]) {
			return mid;
		}else if(target > array[mid]) {
			left = mid + 1;
		}else if(target < array[mid]) {
			right = mid - 1;
		}
		return searchRecursively(array, target, left, right);
		
	}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值