折半查找

mac2022-06-30  107

#include<stdio.h>

#include<iostream>

#include <process.h>

#define OK 1

#define ERROR 0

#define OVERFLOW -2

#define MAXSIZE 100//最大长度

#define INCREMENT 10

using namespace std;

typedef int Status;

typedef int ElemType;//定义Status,ElemType为整型

typedef struct//命名一个新的类型名代替结构体类型

{

ElemType *elem;//顺序表基地址,elem作数组名使用

int length;

int list ;

}Sqlist;//顺序表结构类型

Status InitList(Sqlist &L)

 {  //构造空的顺序表 L

L.elem=new ElemType[MAXSIZE];

if(!L.elem) exit(OVERFLOW);

L.length=0;

return OK;

}

void Work(Sqlist &L)

{  //为顺序表赋值

int i,j;

printf("请输入顺序表的长度:");

scanf("%d",&j);

printf("请输入顺序表各元素:");

for(i=0;i<j;i++)

{

scanf("%d",&L.elem[i]);

L.length++;

}

}

int Bin(Sqlist L)

{

int key;

cout<<"输入查找的关键字:"<<endl;

cin>>key;

int low,mid,high;

low=1;

high=L.length ;

cout<<"关键字在表中的位置为"<<endl;

while(low<=high)

{

mid=(low+high)/2;

if(key==L.elem[mid]) return mid+1;

else if(key<L.elem[mid]) high=mid-1;

else low=mid+1;

}

return 0;

}

 

int main()

{

Sqlist L;

if(InitList(L))

cout<<"初始化成功!"<<endl;

Work(L);

cout<<Bin(L)<<endl;;

}

最新回复(0)