基于线性表的哨兵查找和折半查找

#include<stdio.h>
typedef int KeyType;
#define LIST_SIZE 20
typedef struct RecordType
{
KeyType key;
//OtherType other_data;
}RecordType;


typedef struct RecordList
{
RecordType r[LIST_SIZE+1];
int length;
}RecordList;


void Init(RecordList *l,KeyType k)
{
l->r[0].key=0;
RecordType r[LIST_SIZE+1];
printf("请输入长度:");
scanf("%d",&l->length);
for(int i=1;i<l->length;i++)
{
printf("输入序列中元素:");
scanf("%d",&l->r[i].key);
}
/* for(i=1;i<l.length;i++)
{
printf("初始化的序列为%d ", l.r[i].key);
}*/
}


//哨兵查找
int SeqSearch(RecordList l,KeyType k)
{
int i;
i=l.length;
while(i>=1&&l.r[i].key!=k)
{
i--;
}
if(i>=1)return i;
else return 0;
}

//折半查找
int BinSearch(RecordList l,KeyType k)
{
int low,mid,high;
low=1;
high=l.length;
printf("请输入要查找的值:");
scanf("%d",&k);
while(low<=high)
{
mid=(low+high)/2;
if(k==l.r[mid].key)
{
return (mid);
}
else if(k<l.r[mid].key)
{
high=mid-1;
}
else low=mid+1;
}
return 0;
}

void main()
{
RecordList l;KeyType k;
int i,result1,result2;
Init(&l,k);
printf("请选择:---1.哨兵查找。2.折半查找。 ");
scanf("%d",&i);
switch(i)
{
case 1:
result1=SeqSearch(l,k);
printf("%d ",result1);
case 2:
result2=BinSearch(l,k);
printf("%d ",result2);
default:
printf("Error!");
}
}

原文地址:https://www.cnblogs.com/yjm5/p/6129450.html