#include"malloc.h" /* malloc()等 */
#include"stdio.h"
#include"stdlib.h"
typedef int ElemType;
typedef struct /*静态查找表的顺序存储结构 */
{
ElemType *elem; /* 数据元素存储空间基址,建表时按实际长度分配,0号单元留空 */
int length; /* 表长度 */
}SSTable;
SSTable ST;
void Creat_Seq(SSTable &ST,int n)
{ /* 操作结果: 构造一个含n个数据元素的静态顺序查找表ST(数据来自数组r) */
int i,temp;
ST.elem=(ElemType *)malloc((n) * sizeof(ElemType)); /* 动态生成n个数据元素空间(0号单元不用) */
if(!(ST).elem)
{
printf("ERROR\n");
exit(0);
} /*内存分配失败结束程序*/
for(i=0;i<n;i++)
{
scanf("%d",&temp);
*(ST.elem+i)=temp; /* 依次赋值给ST */
}
ST.length=n;
}
int Search_Bin(int i,int j,ElemType key)
{ /* 在顺序表ST中顺序查找其关键字等于key的数据元素。若找到,则函数值为 */
/* 该元素在表中的位置,否则为0。算法9.1 */
int k=(i+j)/2;
if((key>ST.elem[k]&&key<ST.elem[k+1])||(key>ST.elem[k-1]&&key<ST.elem[k])){
return -1;
}
if(key<ST.elem[k]){
Search_Bin(i,k, key);
}
else if(key>ST.elem[k]){
Search_Bin(k,j, key);
}
else {
return k;
}
}
int main()
{
int loc,key;
int n;
int i=ST.length/2;
scanf("%d",&n);
Creat_Seq(ST,n);
scanf("%d",&key);
loc = Search_Bin(0,ST.length,key);
if(loc!=-1)
printf("The element position is %d.",loc);
else
printf("The element is not exist.");
return 0;
}
SCAU-8621-数据结构-二分查找
最新推荐文章于 2023-09-15 11:59:07 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)