第十四周 项目一(1) 验证算法
2015-11-30 16:13
204 查看
/* Copyright(c)2015,烟台大学计算机学院 All rights reserved. 文件名称:test.cpp 作者:杜佳丽 完成日期:2015年11月30日 问题描述: */
1.折半查找
#include <stdio.h> #define MAXL 100 typedef int KeyType; typedef char InfoType[10]; typedef struct { KeyType key; //KeyType为关键字的数据类型 InfoType data; //其他数据 } NodeType; typedef NodeType SeqList[MAXL]; //顺序表类型 int BinSearch(SeqList R,int n,KeyType k) { int low=0,high=n-1,mid; while (low<=high) { mid=(low+high)/2; if (R[mid].key==k) //查找成功返回 return mid+1; if (R[mid].key>k) //继续在R[low..mid-1]中查找 high=mid-1; else low=mid+1; //继续在R[mid+1..high]中查找 } return 0; } int main() { int i,n=10; int result; SeqList R; KeyType a[]= {1,3,9,12,32,41,45,62,75,77},x=75; for (i=0; i<n; i++) R[i].key=a[i]; result = BinSearch(R,n,x); if(result>0) printf("序列中第 %d 个是 %d\n",result, x); else printf("木有找到!\n"); return 0; }
运行结果:
<img src="https://img-blog.csdn.net/20151130161542870?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />
<pre class="cpp" name="code">2.递归的折半查找算法
#include <stdio.h> #define MAXL 100 typedef int KeyType; typedef char InfoType[10]; typedef struct { KeyType key; //KeyType为关键字的数据类型 InfoType data; //其他数据 } NodeType; typedef NodeType SeqList[MAXL]; //顺序表类型 int BinSearch1(SeqList R,int low,int high,KeyType k) { int mid; if (low<=high) //查找区间存在一个及以上元素 { mid=(low+high)/2; //求中间位置 if (R[mid].key==k) //查找成功返回其逻辑序号mid+1 return mid+1; if (R[mid].key>k) //在R[low..mid-1]中递归查找 BinSearch1(R,low,mid-1,k); else //在R[mid+1..high]中递归查找 BinSearch1(R,mid+1,high,k); } else return 0; } int main() { int i,n=10; int result; SeqList R; KeyType a[]= {1,3,9,12,32,41,45,62,75,77},x=75; for (i=0; i<n; i++) R[i].key=a[i]; result = BinSearch1(R,0,n-1,x); if(result>0) printf("序列中第 %d 个是 %d\n",result, x); else printf("木有找到!\n"); return 0; }
运行结果:
相关文章推荐
- DrawerLayout背景设置的问题,去除阴影
- 规范自己,逐渐蜕变
- iOS textView的使用总结
- OC 实例变量的可见度
- 使用 IBM 中间件实现 SaaS 解决方案,第 4 部分: 单一实例多租户应用程序中资源共享的设计模式
- 解读x86、ARM和MIPS三种主流芯片架构
- java、js 对于四舍五入、向上取整、向下取整
- linux中pipe和dup2详解
- iOS textView的使用总结
- 谈谈跨域请求数据的几种常用的方法
- 2.3物理层下面的传输媒体
- 【第11周 项目2 - 用二叉树求解代数表达式】
- 记录两个关于处理音频的库
- 第14周 项目1.1—验证算法
- IOS学习之数据库(4)--SQLite的应用
- 详解C语言中的符号常量、变量与算术表达式
- Floyd算法的验证
- Beginning Python Chapter3
- Activity生命周期
- Myeclipse自动生成的get set方法 加上文本注释