#include<stdio.h>
#include<stdlib.h>
#define TRUE 1
#define OK 1
#define FALSE 0
#define ERROR 0
#define YES 1
#define NO 0
#define INFEASILE -1
#define OVERFLOW -2
typedef int Status;
typedef int ElemType;
#define LIST_INIT_SIZE 100
#define LISTINNCREMENT 10
typedef struct
{
ElemType* elem;
int length;
int listsize;
}SqList;
//构造空的顺序表L
Status InitList_Sq(SqList& L)
{
L.elem = (ElemType*)malloc(LIST_INIT_SIZE * sizeof(ElemType));
if (!L.elem)
exit(OVERFLOW);
L.length = 0;
L.listsize = LIST_INIT_SIZE;
return OK;
}
Status Great(SqList& L,int n)
{
L.length=n;
printf("请输入线性表中的值:");
for(int i=1;i<=n;i++)
{
int e;
scanf("%d",&e);
L.elem[i]=e;
}
return OK;
}
void print(SqList L)
{
for(int i=1;i<=L.length;i++)
{
printf("%d",L.elem[i]);
}
}
int Bibarysearch(SqList L,int e)
{
int low=1,mid,nofind=-1;
int high=L.length;
while(low<=high)
{
mid=(low+high)/2;
if(e>L.elem[mid])
low=mid+1;
else if(e<L.elem[mid])
high=mid-1;
else
return mid;
}
return nofind;
}
int main()
{
SqList L;
int n;
scanf("%d",&n);
InitList_Sq(L);
Great(L,n);
printf("请输入要查找的元素的值:");
int e;
scanf("%d",&e);
int m;
m=Bibarysearch(L,e);
// print(L);
printf("%d",m);
return 0;
}
二分查找
最新推荐文章于 2023-05-28 13:59:52 发布