第十四周專案1線性表的折半查詢(迴圈法)
阿新 • • 發佈:2018-11-18
/*Copyright (c) 2015, 煙臺大學計算機與控制工程學院
* All rights reserved.
* 檔名稱:H1.cpp
* 作者:辛志勐
* 完成日期:2015年12月2日
* 版本號:VC6.0
* 問題描述:線性表的折半查詢(迴圈法)
* 輸入描述:無
* 程式輸出:圖的基本輸出
*/
#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;
}
知識點總結:使用迴圈將陣列分成兩半,取含有所要查詢元素的那一段,依次去做直到查出。
學習心得:程式碼簡短,知識原理容易理解。