<span style="font-size: 13.3333px;">1.顺序查找</span><p style="font-size: 13.3333px;"></p><p style="margin-top: 0px; margin-bottom: 1.6842em; padding-top: 0px; padding-bottom: 0px; box-sizing: inherit; border: 0px; font-family: 'Noto Serif', serif; font-size: 19px; outline: 0px; vertical-align: baseline; color: rgb(51, 51, 51); line-height: 31.9998px;">2.折半查找</p>#include “stdafx.h”
#include “malloc.h”
#define OVERFLOW -2
#define OK 1
#define LIST_INIT_SIZE 100
#define EQ(a,b) ((a)==(b))
#define LT(a,b) ((a)<(b))
#define LQ(a,b) ((a)>(b))
typedef int KeyType;
typedef struct {
KeyType key;
}ElemType;
typedef struct{
ElemType *elem;
int length;
}SSTable;
int Init(SSTable &S){
S.elem=(ElemType *)malloc(LIST_INIT_SIZE*sizeof(ElemType));
if(!S.elem) return OVERFLOW;
S.length=0;
S.length=LIST_INIT_SIZE;
return OK;
}
int Create(SSTable &ST,int n){
for(int i=1;i<=n;i++){
scanf(“%d”,&ST.elem[i].key);
}
return OK;
}
int Search_Bin(SSTable ST,KeyType key){
int low=1,high=ST.length,mid;
while(low<=high){
mid=(low+high)/2;
if(EQ(key,ST.elem[mid].key)){
printf(“折半查找到的数所在位置是:%d\n”,mid);
return 1;
}else if(LT(key,ST.elem[mid].key))
high=mid-1;
else low=mid+1;
}
return 0;
}
int Search_Seq(SSTable ST,KeyType key){
int i;
ST.elem[0].key=key;
for(i=ST.length;!EQ(ST.elem[i].key,key);–i){
}
printf(“顺序查找得到的顺序是:%d\n”,i);
return OK;
}
int _tmain(int argc, _TCHAR* argv[])
{
int key;
SSTable ST;
Init(ST);
printf(“输入表长\n”);
scanf(“%d”,&ST.length);
printf(“输入元素\n”);
Create(ST,ST.length);
printf(“输入待查元素\n”);
scanf(“%d”,&key);
Search_Seq(ST,key);//顺序查找
Search_Bin(ST,key);//折半查找
return 0;
}