//折半查找算法
#include "stdio.h"
#include "stdlib.h"
#define MAXSIZE 30
typedef int KeyType;
typedef struct{
KeyType key;
char name[20];
}SElemType;
typedef struct{
SElemType elem[MAXSIZE];
int length;
}SSTable;
int Search_Bin(SSTable ST, KeyType key)
{ int high,low,mid;
low = 1;high = ST.length;
while(low <= high){
mid = (low + high)/2;
if (key == ST.elem[mid].key) return mid;
else if (key <= ST.elem[mid].key) high = mid - 1;
else low = mid +1;
}
return 0;
}//Search_Bin
void display(SSTable ST)
{ int i;
for(i=1;i<=ST.length;i++)
printf("%6d",ST.elem[i].key);
printf("\n");
}
int main()
{
int i,pos,key;
SSTable ST;
printf("\nplease input the length of the table:\n ");
scanf("%d",& ST.length);
printf("\nplease input a group of key to creat a list:\n ");
for(i=1;i<= ST.length;i++)
scanf("%d",&ST.elem[i].key);
printf("\noutput the list:\n");
display(ST);
printf("\ninput the find key is :");
scanf("%d", &key);
pos=Search_Bin(ST, key);
printf("\nthe find key is %d, pos is %d\n\n",key,pos );
return 1;
}