折半查找------在一个升序的有序数组中查找某个具体的数字
2016-05-29 21:35
573 查看
非递归法:
= { 1, 5, 12, 36, 45, 98 }; /* * printf("请输入可查找到的数:> ]递归法(不能输出要查找的数字在原数组中的位置): #include <stdio.h> #include <stdlib.h> int binsearch(int x, int *arr, int n); int main() { int x = 0, inter = 0; int arr[] = { 1, 5, 12, 36, 48, 98 }; printf("请输入您要查找的数:> "); scanf_s("%d", &x); inter = binsearch(x, arr, sizeof(arr)/sizeof(arr[0])); if (inter == -1) printf("没找到您要查找的数!\n"); else printf("找到了您要查找的数%d\n", x); system("pause"); return 0; } int binsearch(int x, int *arr, int n) { int mid = (n - 1) / 2; if (n <= 0) return -1; else if (x == *(arr + mid)) /*找到了*/ return mid; else if(x < *(arr + mid)) /*有点大 */ { return binsearch(x, arr+mid-1, mid);/*下一次数组长度为mid */ } else if (x > *(arr + mid)) /*有点小*/ { return binsearch(x, arr+mid+1, mid); } }
相关文章推荐
- 三子连珠游戏
- 全局变量 静态变量 局部变量分析
- 单链表的各种操作
- 替换字符串中的空格
- 一组数中,只有两个数只出现了奇数次,其他所有数都是成对出现的,请找出那两个数
- 冒泡排序函数,可以给任意类型的数据排序,比如整形数组,字符数组,字符串数组等
- 快速排序函数的比较函数
- 二叉树 的先序 中序、后序遍历、层次遍历以及树状打印等操作
- C语言利用结构体实现一个通讯录
- C语言的注释与C++注释的转换
- 两个链表的合并
- 单链表的操作
- 单继承与多继承中的虚函数表和虚函数指针
- C++虚继承中的对象内存布局
- 大道至简阅读笔记01
- shell(十一)切割文件
- [DP] BZOJ 1270 [BeijingWc2008]雷涛的小猫
- HttpClient get请求在HttpResponse中无法获得Location的问题
- 循环
- 天梯匹配系统 - 简单实现