分块查找算法
问题:明白思想,其他的没什么,记得结构体为指针时一定要动态分配内存。
代码:
#include <iostream> #include <cstdlib> using namespace std; #define MAXL 20 typedef struct seq { int key[MAXL]; int len; }data; typedef struct table { int start; int end; int d; }index[4]; int block_search(index s,data *list, int key) //分块查找 { int i=0; int j; while (i<4&&key>s[i].d) //确定块的地址 i++; if (i>=4) return -1; for (j=s[i].start;j<=s[i].end;j++) { if (list->key[j]==key) return j; } if (j>s[i].end) return -1; } int main() { data *list; index s; int i,j,p; int key; cout<< "/" << "分块查找" << "/" <<endl; cout<< "---------------------" <<endl; list=(data *) malloc ( sizeof ( struct seq)); if (!list) cout<< "allocate fail" <<endl; cout<< "input the len:" ; cin>>list->len; for (i=0;i<list->len;i++) { cin>>list->key[i]; } cout<< "output the list:" <<endl; for (i=0;i<list->len;i++) { cout<<list->key[i]<< " " ; } cout<<endl; for (j=0;j<4;j++) { cin>>s[j].start>>s[j].end>>s[j].d; } cout<< "please input the key:" ; cin>>key; p=block_search(s,list,key); if (p==-1) cout<< "can not find" <<endl; else cout<< "the key pos is " <<p<<endl; return 0; } |
运行截图:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· [AI/GPT/综述] AI Agent的设计模式综述