第十四周项目1-(1)验证折半查找算法
2015-12-04 08:15
369 查看
问题:
/*
* Copyright (c)2015,烟台大学计算机与控制工程学院
* All rights reserved.
* 文件名称:项目1-1.cbp
* 作 者:李艺
* 完成日期:2015年12月4日
* 版 本 号:v1.0
* 问题描述:验证折半查找算法
* 输入描述:无
* 程序输出:测试数据
*/
代码:
#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[]= {12,18,24,35,47,50,62,83,90,115,134},x=100;
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;
}
运行结果:
x=47时
x=90时
x=100时
知识点总结:
折半查找算法的验证。
/*
* Copyright (c)2015,烟台大学计算机与控制工程学院
* All rights reserved.
* 文件名称:项目1-1.cbp
* 作 者:李艺
* 完成日期:2015年12月4日
* 版 本 号:v1.0
* 问题描述:验证折半查找算法
* 输入描述:无
* 程序输出:测试数据
*/
代码:
#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[]= {12,18,24,35,47,50,62,83,90,115,134},x=100;
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;
}
运行结果:
x=47时
x=90时
x=100时
知识点总结:
折半查找算法的验证。
相关文章推荐
- 十四周 项目三-是否二叉排序树
- 【模板】字符串算法-字符串最小表示法
- python --for循环
- (第十二周项目1)图基本算法库
- DVWA系列之4 利用SQLMap进行medium级别注入
- DVWA系列之4 利用SQLMap进行medium级别注入
- test
- python --if语句
- Linux下vsftpd的简单应用(一)
- cocos2d-js开发总结
- 验证分块查找算法
- 博客开张 自嗨自勉
- nagios 自定义插件demo
- [LeetCode]Two Sum II - Input array is sorted
- An universal algorithm design of fixed length substring locating
- An universal algorithm design of fixed length substring locating
- 第14周 项目2 - 二叉树排序树中查找的路径
- 堆和栈的区别
- <meta>标签中的name与http-equiv
- bzoj2337: [HNOI2011]XOR和路径