第十四周專案1(1)-驗證演算法
阿新 • • 發佈:2019-01-04
問題及程式碼:
#include <stdio.h> #define MAXL 100 typedef int KeyType; typedef char InforType[10]; typedef struct { KeyType key; InforType 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=(high+low)/2; if(R[mid].key==k) return mid+1; if(R[mid].key>k) high=mid-1; else low=mid+1; } return 0; } int main() { int i,n=10; int result; SeqList R; KeyType a[]= {12,18,24,35,47,50,62,83,90,115,134},x; for (i=0; i<n; i++) R[i].key=a[i]; result = BinSearch(R,n,x); x=90; if(result>0) printf("序列中第 %d 個是 %d\n",result, x); else printf("木有找到!\n"); result = BinSearch(R,n,x); x=47; if(result>0) printf("序列中第 %d 個是 %d\n",result, x); else printf("木有找到!\n"); result = BinSearch(R,n,x); x=100; if(result>0) printf("序列中第 %d 個是 %d\n",result, x); else printf("木有找到!\n"); result = BinSearch(R,n,x); return 0; }
執行結果: