二分查找 (循环、递归两种方法)
2017-10-23 10:35
597 查看
二分查找 (binary search)
循环实现
int BinarySearch(int *a,int len,int target) { int low,high,mid; low=0; high=len-1; while (low<=high) { mid=(low+high)/2; if (a[mid]==target) return mid+1; else if(a[mid]<target) low=mid+1; else if (a[mid]>target) high=mid-1; } return NOTFOUND; }
递归实现
int IterBiSearch(int *a, const int x, int begin, int end) { int mid; mid = (begin + end) / 2; if (x == a[mid]) return mid+1; else if (x < a[mid]) return IterBiSearch(a, x, begin, mid - 1); else if (x > a[mid]) return IterBiSearch(a, x, mid + 1, end); return NOTFOUND; }
主函数测试
int main() { int A[]={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}; int toFind; scanf("%d",&toFind); int length=sizeof(A)/sizeof(*A); //int result=(BinarySearch(A,length,toFind)); int result=IterBiSearch(A, toFind, 0, length-1); switch (result%10) { case 1: printf("%d is the %dst element of the sequence.\n",toFind,result); break; case 2: printf("%d is the %ded element of the sequence.\n",toFind,result); break; case 3: printf("%d is the %drd element of the sequence.\n",toFind,result); break; case -1: printf("Can't find %d",toFind); default: printf("%d is the %dth element of the sequence.\n",toFind,result); break; } return 0; }
运行结果
相关文章推荐
- 使用递归和非递归两种方法实现二分查找!!!
- 练习题013:二分查找(递归和非递归两种方法)
- 二分查找的两种实现方式--循环和递归
- C语言经典算法(九)——递归实现二分查找的两种方法
- 二分查找的两种实现(循环与递归)
- 二分查找的循环和递归方法
- LeetCode 374 使用循环代替递归的二分查找从而避免栈溢出的错误
- 二分查找的两种实现方法
- C#统计给定的文本中字符出现的次数,使用循环和递归两种方法
- 用java语言,操作给定的二叉树,将其变换为源二叉树的镜像(递归和循环两种方法)
- 递归和循环两种方法完成树的镜像转换
- C++之二分查找/折半查找(非递归和递归两种方式)
- 输入一颗二元查找树,将该树转换为它的镜像, 即在转换后的二元查找树中,左子树的结点都大于右子树的结点。 用递归和循环两种方法完成树的镜像转换:
- 二分求幂—递归非递归两种方法
- 【C语言】用递归和循环两种方法实现单链表倒置
- 递归一题三解-将二分查找树(BST)转化成循环双链表(DLL)
- php二分查找的两种实现方法
- 二分查找 递归实现 和 循环实现
- ruby数组和哈希表的区别,递归,二分查找方法
- 二分查找的尾递归和循环形式的分析