数据结构与算法学习之路:二分查找的非递归和递归算法
2014-11-11 20:55
555 查看
一、何为二分查找?
二分查找又称折半查找,优点是比较次数少,查找速度快,平均性能好;其缺点是要求待查表为有序表,且插入删除困难。因此,折半查找方法适用于不经常变动而查找频繁的有序列表。
二分查找的基本思想是:在有序序列中,通过与序列段中间的数作比较,减少多余的比较(例如key<mid,则在start和mid-1之间查找,反之在mid+1和end之间查找)
二、具体代码实现:
(本代码段并没有考虑溢出、low,high大小超出数据类型等等情况,有兴趣的读者可以自行搜索相关内容或者参考书籍了解)
二分查找又称折半查找,优点是比较次数少,查找速度快,平均性能好;其缺点是要求待查表为有序表,且插入删除困难。因此,折半查找方法适用于不经常变动而查找频繁的有序列表。
二分查找的基本思想是:在有序序列中,通过与序列段中间的数作比较,减少多余的比较(例如key<mid,则在start和mid-1之间查找,反之在mid+1和end之间查找)
二、具体代码实现:
(本代码段并没有考虑溢出、low,high大小超出数据类型等等情况,有兴趣的读者可以自行搜索相关内容或者参考书籍了解)
#include <stdio.h> #include <stdlib.h> #define SUCESS 1 #define FALSE 0 #define MAXSIZE 10 int Binary_Search_Version1(int *test, int start, int end, int key); int Binary_Search_Version2(int *test, int start, int end, int key); int main(){ int test[MAXSIZE] = { 1, 9, 22, 26, 34, 49, 52, 63, 78, 89 }; int search; printf("请输入要查找地数:\t"); scanf("%d", &search); if (Binary_Search_Version1(test, 0, MAXSIZE - 1, search)) printf("\n找到了.\n"); else printf("没找到\n"); if (Binary_Search_Version2(test, 0, MAXSIZE - 1, search)) printf("\n找到了.\n"); else printf("没找到\n"); } //递归算法 int Binary_Search_Version1(int *test, int start, int end, int key){ int mid, low = start, high = end; if (low > high) return FALSE; mid = (low + high) / 2; if (key == test[mid]) return SUCESS; else if (key < test[mid]) Binary_Search_Version1(test, low, mid - 1, key); else Binary_Search_Version1(test, mid + 1, high, key); } //非递归算法 int Binary_Search_Version2(int *test, int start, int end, int key){ int mid, low = start, high = end; while (low <= high){ mid = (low + high) / 2; if (key == test[mid]) return SUCESS; else if (key < test[mid]){ high = --mid; } else start = ++mid; } return FALSE; }
相关文章推荐
- java数据结构与算法-递归二分查找
- 【数据结构与算法】二分查找递归非递归实现
- 数据结构与算法学习之路:LIS——最长递增序列的动态规划算法和二分思想算法
- 【算法学习笔记】10.数据结构基础 二叉树初步练习3(遍历与递归复习)
- 数据结构:二分查找的递归与非递归实现--C实现
- 数据结构与算法------二分查找
- 数据结构与算法学习笔记——二叉树重构(递归)
- 【算法学习笔记】10.数据结构基础 二叉树初步练习3(遍历与递归复习)
- 数据结构与算法题目集(中文)4-10 二分查找 (20分)
- 别样数据结构与算法学习(六)查找
- 【数据结构与算法】二分查找
- 算法学习---基本数据类型的数组二分查找实现
- 【数据结构与算法学习笔记】PART1:算法分析(计算,计算模型,大O记号,算法分析,迭代与递归,动态控制)
- 数据结构与算法学习笔记——二叉树遍历(一)(递归、迭代)
- 【数据结构与算法】二分查找
- 数据结构与算法-折半查找(二分查找)
- 数据结构与算法学习之路:直接插入排序
- 【数据结构与算法】【查找】折半查找(二分查找)的代码实现
- 数据结构与算法-二分查找
- 【数据结构与算法】二分查找