二分查找的两种实现方式
2017-03-26 21:39
537 查看
笔者在这里给出二分查找的两种实现方式。
一. 第一种是健忘版的二分查找,即不管是否已经找到target,查找算法都继续对表进行再分,直到剩下的表的长度为1。
递归实现如下:
非递归实现如下:
二. 第二种是识别想等的二分查找,即在继续二分前判断当前的值是否等于target,减少不必要的重复。
递归实现如下:
非递归实现如下:
一. 第一种是健忘版的二分查找,即不管是否已经找到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; }
相关文章推荐
- javascript中二分查找法的两种实现方式
- java实现二分查找-两种方式
- 二分查找的两种实现方式--循环和递归
- 二分查找的两种实现方式
- java两种实现二分查找方式
- 算法:两种方式(递归/循环)实现二分查找
- 二分查找的两种实现方式(JAVA)
- 二分查找的两种实现方式(递归和非递归)--python实现
- 经典案例,二分查找的三种实现方式
- 二分查找的两种方式
- 二分查找的两种实现
- 二分查找的两种实现(循环与递归)
- C++之二分查找/折半查找(非递归和递归两种方式)
- 二分查找的递归/非递归方式C++实现
- 二分查找的两种方式
- java实现 二分查找 非递归与递归2种方式
- 二分查找的两种基本方式
- 使用递归和非递归两种方法实现二分查找!!!
- 二分查找的两种实现方法
- C语言经典算法(九)——递归实现二分查找的两种方法