/*
*Copyright(c) 2015,煙臺大學計算機學院
*All rights reserved.
*文件名稱:test.cpp
*作者:林莉
*完成日期:2015年11月30日
*版本:v1.0
*
*問題描述:請用有序表{12,18,24,35,47,50,62,83,90,115,134}作爲測試序列,分別對查找90、47、100進行測試
*輸入描述:無
*輸出描述:所得結果。
*/
#include <stdio.h>
#define MAXL 100
typedef int KeyType;
typedef char InfoType[10];
typedef struct
{
KeyType key; //KeyType爲關鍵字的數據類型
InfoType data; //其他數據
} NodeType;
typedef NodeType SeqList[MAXL]; //順序表類型
int BinSearch(SeqList R,int n,KeyType k)
{
int low=0,high=n-1,mid;
while (low<=high)
{
mid=(low+high)/2;
if (R[mid].key==k) //查找成功返回
return mid+1;
if (R[mid].key>k) //繼續在R[low..mid-1]中查找
high=mid-1;
else
low=mid+1; //繼續在R[mid+1..high]中查找
}
return 0;
}
int main()
{
int i,n=10;
int result;
SeqList R;
KeyType a[]= {1,3,9,12,32,41,45,62,75,77},x=75;
for (i=0; i<n; i++)
R[i].key=a[i];
result = BinSearch(R,n,x);
if(result>0)
printf("序列中第 %d 個是 %d\n",result, x);
else
printf("木有找到!\n");
return 0;
}
運行結果: