折半查找

#include <iostream>

using namespace std;

#define MAXSIZE 50

typedef int KeyType;

typedef struct { KeyType key; } ElemType;

typedef struct { ElemType *R; int length; } SSTable;

void Create(SSTable &T) { int i; T.R=new ElemType[MAXSIZE+1]; cin>>T.length; for(i=1;i<=T.length;i++) cin>>T.R[i].key; }

int Search_Bin(SSTable T, KeyType k);

int main ()

{ SSTable T;

KeyType k;

Create(T);

cin>>k;

int pos=Search_Bin(T,k);

if(pos==0) cout<<"NOT FOUND"<<endl;

else cout<<pos<<endl;

return 0;

}

int Search_Bin(SSTable T, KeyType k)
{
int min=1,max=T.length;
int mid=(min+max)/2;
while(max>=min)//折半查找循环,左右边界作为循环条件比(1)循环运行效率高;
{
if(k==T.R[mid].key)
break;
else{
if(k>T.R[mid].key)
{ min=mid+1;
mid=(min+max)/2;
}
else
{
max=mid-1;
mid=(min+max)/2;
}
}
}
if(min<=max)
return mid;
else
return 0;
}

 

posted @ 2023-05-11 20:54  mo寒流xing  阅读(22)  评论(0)    收藏  举报