#include "stdafx.h"
#include <iostream.h>
#include <malloc.h>

//顺序表上的查找
int const maxsize=10;
typedef struct


{
int key;
}rec;

typedef struct


{
rec item[maxsize+1];
int n; //最后一个元素下标
}sqtable;

int search_sqtable(sqtable R,int key)


{
//设置第0个元素为待查键,它起岗哨的作用,保证循环肯定有匹配的键.没有用正常的循环过程是为了减化操作,提高效率
R.item[0].key=key;
int i=R.n;
while(R.item[i].key!=key)
i--;
return i;
}
//我的书中在讲此节时错误很多,多为印刷错误,我的书应该是正版的,不知道其它如何.书中的
int binsearch(sqtable R,int key)


{
int low=1,hig=R.n;
while(low<=hig)

{
int mid=(low+hig)/2;
if (R.item[mid].key==key)

{
return mid;
}
else if (R.item[mid].key>key)

{
low=mid+1; //书中此处为low=low+1,应该是印刷错误,此处改为low=mid+1
}
else if (R.item[mid].key<key)

{
hig=mid-1;
}
}
return 0;
}
int main(int argc, char* argv[])


{
sqtable table;
for(int i=1;i<11;i++)

{
table.item[i].key=i+100;
}
table.n=5;
cout<<"使用顺序查找:"<<search_sqtable(table,103)<<endl;
cout<<"使用二分查找:"<<binsearch(table,103)<<endl;
return 0;
}
一点说明:为什么在标题中要嵌入英文?原因是为了能够让国外的网友能查询到这篇文章。平常在Google上查资料的时候,经常参考国外网友的博客,帮助我解决了很多问题,所以我也想让他们能够参考我写的内容。当然文中我不可能全部译为英文,所以我尽量把代码粘全,靠代码说话吧。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· C++代码改造为UTF-8编码问题的总结
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
· Java 中堆内存和栈内存上的数据分布和特点
· What?废柴, 还在本地部署DeepSeek吗?Are you kidding?
· 程序员转型AI:行业分析
· 深入集成:使用 DeepSeek SDK for .NET 实现自然语言处理功能
· 为DeepSeek添加本地知识库
· .NET程序员AI开发基座:Microsoft.Extensions.AI