您的位置:首页 > 其它

二分查找的两种实现方式

2017-03-26 21:39 537 查看
笔者在这里给出二分查找的两种实现方式。

一. 第一种是健忘版的二分查找,即不管是否已经找到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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  二分查找 算法 递归