平均查找长度:logn
typedef int KeyType;
KeyType *elem;
int length;
}SSTable;
int Search_Bin(SSTable ST,KeyType key)
{
int low = 1,high = ST.length,mid;
while(low <= high)
{
mid = (low + high)/2;
if(key == ST.elem[mid])
return mid;
else if(key < ST.elem[mid])
high = mid - 1;
else
low = mid + 1;
}
return 0;
}
int main(int argc, char* argv[])
{
int i,key;
SSTable ST;
ST.elem = (KeyType *)malloc(sizeof(KeyType));
printf("Please input the length of array:");
scanf("%d",&ST.length);
for(i = 1;i <= ST.length ; i++)
{
printf("Please input the %dth element:",i);
scanf("%d",&ST.elem[i]);
}
printf("\nPlease input the data to find:");
scanf("%d",&key);
i = Search_Bin(ST,key);
if(0 == i)
printf("The data is not exist in this array.\n");
else
printf("The location of %d is:%d\n",key,i);
return 0;
}