二分查找的两种实现方式

笔者在这里给出二分查找的两种实现方式。

一. 第一种是健忘版的二分查找,即不管是否已经找到target,查找算法都继续对表进行再分,直到剩下的表的长度为1。

递归实现如下:

Error_code recursive_binary_1(const Ordered_list &the_list, const Key &target, int bottom, int top, int &position) {
	Record data;
	if (bottom < top) {
		int mid = (bottom+top)/2;
		the_list.retrieve(mid, data); //获取mid位置的值并赋给data
		//注意下面两个语句不是对称的
		if (data < target) return recursive_binary_1(the_list, target, mid+1, top, position);
		else return recursive_binary_1(the_list, target, bottom, mid, position);
	}
	else if (top < bottom) return not_present;
	else {
		position = bottom;
		the_list.retrieve(position, data);
		if (data == target) return success;
		else return not_present;
	}
}

非递归实现如下:

Error_code recursive_binary_1(const Ordered_list &the_list, const Key &target, int &position) {
	Record data;
	int bottom = 0, top = the_list.size()-1;
	while (bottom < top) {
		int mid = (bottom+top)/2;
		the_list.retrieve(mid, data);
		if (data < target) bottom = mid+1;
		else top = mid;
	}
	else if (top < bottom) return not_present;
	else {
		position = bottom;
		the_list.retrieve(position, data);
		if (data == target) return success;
		else return not_present;
	}
}
需要注意的是健忘版的二分查找在二分时bottom和top的更新不是对称的,上面的条件总是会把mid放入两个区间中较低的一个,即在整个查找过程中bottom<=mid<top。上面的二分查找是一种简单形式的二分查找,它做了很多不必要的重复,因为它不能再继续重复前识别已找到了目标。

二. 第二种是识别想等的二分查找,即在继续二分前判断当前的值是否等于target,减少不必要的重复。

递归实现如下:

Error_code recursive_binary_2(const Ordered_list &the_list, const Key &target, int bottom, int top, int &position) {
	Record data;
	if (bottom <= top) {
		int mid = (bottom+top)/2;
		the_list.retrieve(mid, data); //获取mid位置的值并赋给data
		if (data == target) return {
			position = mid;
			success;
		}
		//下面的递归语句是对称的了
		if (data < target) return recursive_binary_2(the_list, target, mid+1, top, position);
		else return recursive_binary_2(the_list, target, bottom, mid-1, position);
	}
	return not_present;
}

非递归实现如下:

Error_code recursive_binary_1(const Ordered_list &the_list, const Key &target, int &position) {
	Record data;
	int bottom = 0, top = the_list.size()-1;
	while (bottom <= top) {
		position = (bottom+top)/2;
		the_list.retrieve(position, data);
		if (data == target) return success;
		if (data < target) bottom = position+1;
		else top = position-1;
	}
	return not_present;
}



  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值