折半查找又为二分查找,对待查找的列表有两个要求:1.必须采用顺序存储结构。
2.必须按关键字大小顺序排列。
#include<stdio.h>
#define Max 100
typedef struct {int key;int other;
}RecordType;
typedef struct {RecordType r[Max];int lenght;
}Recordlist;
int SeqSearch(Recordlist l,int k)
{int low=1,high=l.lenght,mid;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;
}
int main()
{Recordlist l;int k,i;scanf("%d",&l.lenght);for(i=0;i<l.lenght;i++){scanf("%d",&l.r[i].key);}scanf("%d",&k);i=SeqSearch(l,k);if(i!=0)printf("%d\n",i+1);else printf("no\n");return 0;
}