#include<iostream> using namespace std; #define MAXSIZE 100; #define OK 1; typedef struct { int key; }ElemType; typedef struct { ElemType *R; int length;}SSTable; int InitList_SSTable(SSTable &L) { L.R=new ElemType[MAXSIZA] if(!L.R) { cout<<"初始化错误"; return 0; } L.length=0; return OK; } int Insert_SSTable(SSTable &L) { int j=1; for(int i=1;i<MAXSIZE;i++) { L.R[i].key=j; L.length++; j++; } return 1; } int Search_Bin(SSTable ST,int key) { int low=1,high=ST.length; int mid; while((low<=high)/2) { mid=(low+high)/2; if(key==ST.R[mid].key) return mid; else if(key<ST.R[mid].key) high=mid-1; else low=mid+1; } return 0; } void Show_End(int result,int testkey) { if(result==0) cout<<"未找到"<<testkey<<endl; else cout<<"找到"<<testkey<<"位置为"<<result<<endl; return; } void main() { SSTable ST; InitList_SSTable(ST); Insert_SSTable(ST); int testkey=7,testkey2=200; int result; result=Search_Bin(ST,testkey2); Show_End(result,testkey2); }
时间: 2024-04-26 07:20:36 浏览: 81
这段代码是一个简单的静态查找算法——二分查找的实现。其中定义了一个ElemType结构体表示表中元素的类型,以及一个SSTable结构体表示静态顺序表。函数InitList_SSTable用于初始化静态顺序表,函数Insert_SSTable用于向静态顺序表中插入元素,函数Search_Bin用于在静态顺序表中查找指定元素,并返回其位置。最后,函数main中调用这些函数实现了一个简单的测试,输出了查找结果。
但是,代码中存在一些错误。在宏定义中MAXSIZE后面应该去掉分号,否则会导致编译错误。InitList_SSTable函数中new分配内存的语句后面也缺少了分号,同样会导致编译错误。在while循环中的判断条件应该是(low<=high),而不是(low<=high)/2。此外,代码中没有释放动态分配的内存空间,存在内存泄漏的风险。
相关问题
//折半查找 #include<iostream> #include<fstream> #include<string> #include <algorithm> using namespace std; #define MAXSIZE 10000 #define KEYSIZE 10//关键词个数 #define OK 0 #define ERROR -1 typedef string KeyType; typedef struct { KeyType key;//关键字域 int count;//词频 int index;//在关键词列表中的序号 }ElemType; typedef struct { ElemType *R;//存储空间基地址 int length;//当前长度 }SSTable; //关键词列表 KeyType key[KEYSIZE] = {"little","prince","sheep","flowers","believe","stars","one","my","he","the"}; //初始化一个空的查找表ST //ST的0号单元闲置不用 int InitSSTable(SSTable &ST) { /*-----------代码开始--------------*/ /*-----------代码结束--------------*/ return OK; }
折半查找(二分查找)是一种高效的查找算法,它要求待查找的序列必须是有序的。它的基本思想是:首先确定待查找区间的中间位置,然后将待查找关键字与中间位置关键字进行比较,如果相等则查找成功;否则根据比较结果确定下一步查找的区间,直到找到所需的关键字或者区间为空为止。
在代码中,SSTable是一个结构体,它包含了一个关键字数组和一些其他的属性,如当前长度等。InitSSTable函数的作用是初始化一个空的查找表ST,即将ST中的R指向一个新分配的空间,并将其长度初始化为0。
直接插入排序。 #include <iostream> #define MAXSIZE 1000 using namespace std; typedef struct { int key; char *otherinfo; }ElemType; typedef struct { ElemType *r; int length; }SqList; void InsertSort(SqList &L) { int i,j; for(i=2;i<=
L.length;i++) { //从第二个元素开始插入排序 if(L.r[i].key<L.r[i-1].key) { L.r[0]=L.r[i]; //哨兵 L.r[i]=L.r[i-1]; for(j=i-2;L.r[0].key<L.r[j].key;j--) { //从后往前比较 L.r[j+1]=L.r[j]; //记录后移 } L.r[j+1]=L.r[0]; //插入到正确位置 } } }
以上是直接插入排序的 C++ 代码实现,使用了哨兵来简化代码。对于一个长度为n的序列,平均时间复杂度为O(n^2),最坏时间复杂度为O(n^2),空间复杂度为O(1)。